download.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. "io"
  7. "path"
  8. "github.com/gogits/gogs/modules/base"
  9. "github.com/gogits/gogs/modules/git"
  10. "github.com/gogits/gogs/modules/middleware"
  11. )
  12. func ServeBlob(ctx *middleware.Context, blob *git.Blob) error {
  13. dataRc, err := blob.Data()
  14. if err != nil {
  15. return err
  16. }
  17. buf := make([]byte, 1024)
  18. n, _ := dataRc.Read(buf)
  19. if n > 0 {
  20. buf = buf[:n]
  21. }
  22. _, isTextFile := base.IsTextFile(buf)
  23. if isTextFile {
  24. charset, _ := base.DetectEncoding(buf)
  25. if charset != "UTF-8" {
  26. ctx.Resp.Header().Set("Content-Type", "text/plain; charset="+charset)
  27. }
  28. } else {
  29. _, isImageFile := base.IsImageFile(buf)
  30. if !isImageFile {
  31. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+path.Base(ctx.Repo.TreeName))
  32. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  33. }
  34. }
  35. ctx.Resp.Write(buf)
  36. _, err = io.Copy(ctx.Resp, dataRc)
  37. return err
  38. }
  39. func SingleDownload(ctx *middleware.Context) {
  40. blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreeName)
  41. if err != nil {
  42. if err == git.ErrNotExist {
  43. ctx.Handle(404, "GetBlobByPath", nil)
  44. } else {
  45. ctx.Handle(500, "GetBlobByPath", err)
  46. }
  47. return
  48. }
  49. if err = ServeBlob(ctx, blob); err != nil {
  50. ctx.Handle(500, "ServeBlob", err)
  51. }
  52. }