download.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package repo
  2. import (
  3. "gitote/gitote/pkg/context"
  4. "gitote/gitote/pkg/setting"
  5. "gitote/gitote/pkg/tool"
  6. "io"
  7. "path"
  8. "gitlab.com/gitote/git-module"
  9. )
  10. func ServeData(c *context.Context, name string, reader io.Reader) error {
  11. buf := make([]byte, 1024)
  12. n, _ := reader.Read(buf)
  13. if n >= 0 {
  14. buf = buf[:n]
  15. }
  16. if !tool.IsTextFile(buf) {
  17. if !tool.IsImageFile(buf) {
  18. c.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"")
  19. c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  20. }
  21. } else if !setting.Repository.EnableRawFileRenderMode || !c.QueryBool("render") {
  22. c.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
  23. }
  24. c.Resp.Write(buf)
  25. _, err := io.Copy(c.Resp, reader)
  26. return err
  27. }
  28. func ServeBlob(c *context.Context, blob *git.Blob) error {
  29. dataRc, err := blob.Data()
  30. if err != nil {
  31. return err
  32. }
  33. return ServeData(c, path.Base(c.Repo.TreePath), dataRc)
  34. }
  35. func SingleDownload(c *context.Context) {
  36. blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath)
  37. if err != nil {
  38. if git.IsErrNotExist(err) {
  39. c.Handle(404, "GetBlobByPath", nil)
  40. } else {
  41. c.Handle(500, "GetBlobByPath", err)
  42. }
  43. return
  44. }
  45. if err = ServeBlob(c, blob); err != nil {
  46. c.Handle(500, "ServeBlob", err)
  47. }
  48. }