download.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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/conf"
  13. "gogs.io/gogs/internal/tool"
  14. )
  15. func serveData(c *context.Context, name string, r io.Reader) error {
  16. buf := make([]byte, 1024)
  17. n, _ := r.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 !conf.Repository.EnableRawFileRenderMode || !c.QueryBool("render") {
  32. c.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
  33. }
  34. if _, err := c.Resp.Write(buf); err != nil {
  35. return fmt.Errorf("write buffer to response: %v", err)
  36. }
  37. _, err = io.Copy(c.Resp, r)
  38. return err
  39. }
  40. func ServeBlob(c *context.Context, blob *git.Blob) error {
  41. dataRc, err := blob.Data()
  42. if err != nil {
  43. return err
  44. }
  45. return serveData(c, path.Base(c.Repo.TreePath), dataRc)
  46. }
  47. func SingleDownload(c *context.Context) {
  48. blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath)
  49. if err != nil {
  50. if git.IsErrNotExist(err) {
  51. c.Handle(404, "GetBlobByPath", nil)
  52. } else {
  53. c.Handle(500, "GetBlobByPath", err)
  54. }
  55. return
  56. }
  57. if err = ServeBlob(c, blob); err != nil {
  58. c.Handle(500, "ServeBlob", err)
  59. }
  60. }