download.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. "fmt"
  7. "io"
  8. "net/http"
  9. "path"
  10. "github.com/gogs/git-module"
  11. "gogs.io/gogs/internal/context"
  12. "gogs.io/gogs/internal/setting"
  13. "gogs.io/gogs/internal/tool"
  14. )
  15. func ServeData(c *context.Context, name string, reader io.Reader) error {
  16. buf := make([]byte, 1024)
  17. n, _ := reader.Read(buf)
  18. if n >= 0 {
  19. buf = buf[:n]
  20. }
  21. commit, err := c.Repo.Commit.GetCommitByPath(c.Repo.TreePath)
  22. if err != nil {
  23. return fmt.Errorf("GetCommitByPath: %v", err)
  24. }
  25. c.Resp.Header().Set("Last-Modified", commit.Committer.When.Format(http.TimeFormat))
  26. if !tool.IsTextFile(buf) {
  27. if !tool.IsImageFile(buf) {
  28. c.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"")
  29. c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  30. }
  31. } else if !setting.Repository.EnableRawFileRenderMode || !c.QueryBool("render") {
  32. c.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
  33. }
  34. c.Resp.Write(buf)
  35. _, err = io.Copy(c.Resp, reader)
  36. return err
  37. }
  38. func ServeBlob(c *context.Context, blob *git.Blob) error {
  39. dataRc, err := blob.Data()
  40. if err != nil {
  41. return err
  42. }
  43. return ServeData(c, path.Base(c.Repo.TreePath), dataRc)
  44. }
  45. func SingleDownload(c *context.Context) {
  46. blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath)
  47. if err != nil {
  48. if git.IsErrNotExist(err) {
  49. c.Handle(404, "GetBlobByPath", nil)
  50. } else {
  51. c.Handle(500, "GetBlobByPath", err)
  52. }
  53. return
  54. }
  55. if err = ServeBlob(c, blob); err != nil {
  56. c.Handle(500, "ServeBlob", err)
  57. }
  58. }