download.go 1.2 KB

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