download.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 ServeData(ctx *middleware.Context, name string, reader io.Reader) error {
  13. buf := make([]byte, 1024)
  14. n, _ := reader.Read(buf)
  15. if n > 0 {
  16. buf = buf[:n]
  17. }
  18. _, isTextFile := base.IsTextFile(buf)
  19. if isTextFile {
  20. charset, _ := base.DetectEncoding(buf)
  21. if charset != "UTF-8" {
  22. ctx.Resp.Header().Set("Content-Type", "text/plain; charset="+charset)
  23. }
  24. } else {
  25. _, isImageFile := base.IsImageFile(buf)
  26. if !isImageFile {
  27. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+path.Base(ctx.Repo.TreeName))
  28. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  29. }
  30. }
  31. ctx.Resp.Write(buf)
  32. _, err := io.Copy(ctx.Resp, reader)
  33. return err
  34. }
  35. func ServeBlob(ctx *middleware.Context, blob *git.Blob) error {
  36. dataRc, err := blob.Data()
  37. if err != nil {
  38. return err
  39. }
  40. return ServeData(ctx, ctx.Repo.TreeName, dataRc)
  41. }
  42. func SingleDownload(ctx *middleware.Context) {
  43. blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreeName)
  44. if err != nil {
  45. if err == git.ErrNotExist {
  46. ctx.Handle(404, "GetBlobByPath", nil)
  47. } else {
  48. ctx.Handle(500, "GetBlobByPath", err)
  49. }
  50. return
  51. }
  52. if err = ServeBlob(ctx, blob); err != nil {
  53. ctx.Handle(500, "ServeBlob", err)
  54. }
  55. }