download.go 1.4 KB

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