download.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. _, isImageFile := base.IsImageFile(buf)
  24. ctx.Resp.Header().Set("Content-Type", "text/plain")
  25. if !isTextFile && !isImageFile {
  26. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+path.Base(ctx.Repo.TreeName))
  27. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  28. }
  29. ctx.Resp.Write(buf)
  30. _, err = io.Copy(ctx.Resp, dataRc)
  31. return err
  32. }
  33. func SingleDownload(ctx *middleware.Context) {
  34. blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreeName)
  35. if err != nil {
  36. if err == git.ErrNotExist {
  37. ctx.Handle(404, "GetBlobByPath", nil)
  38. } else {
  39. ctx.Handle(500, "GetBlobByPath", err)
  40. }
  41. return
  42. }
  43. if err = ServeBlob(ctx, blob); err != nil {
  44. ctx.Handle(500, "ServeBlob", err)
  45. }
  46. }