download.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. "net/http"
  8. "path"
  9. "github.com/gogs/git-module"
  10. "gogs.io/gogs/internal/conf"
  11. "gogs.io/gogs/internal/context"
  12. "gogs.io/gogs/internal/gitutil"
  13. "gogs.io/gogs/internal/tool"
  14. )
  15. func serveData(c *context.Context, name string, data []byte) error {
  16. commit, err := c.Repo.Commit.CommitByPath(git.CommitByRevisionOptions{Path: c.Repo.TreePath})
  17. if err != nil {
  18. return fmt.Errorf("get commit by path %q: %v", c.Repo.TreePath, err)
  19. }
  20. c.Resp.Header().Set("Last-Modified", commit.Committer.When.Format(http.TimeFormat))
  21. if !tool.IsTextFile(data) {
  22. if !tool.IsImageFile(data) {
  23. c.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"")
  24. c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  25. }
  26. } else if !conf.Repository.EnableRawFileRenderMode || !c.QueryBool("render") {
  27. c.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
  28. }
  29. if _, err := c.Resp.Write(data); err != nil {
  30. return fmt.Errorf("write buffer to response: %v", err)
  31. }
  32. return nil
  33. }
  34. func ServeBlob(c *context.Context, blob *git.Blob) error {
  35. p, err := blob.Bytes()
  36. if err != nil {
  37. return err
  38. }
  39. return serveData(c, path.Base(c.Repo.TreePath), p)
  40. }
  41. func SingleDownload(c *context.Context) {
  42. blob, err := c.Repo.Commit.Blob(c.Repo.TreePath)
  43. if err != nil {
  44. c.NotFoundOrServerError("get blob", gitutil.IsErrRevisionNotExist, err)
  45. return
  46. }
  47. if err = ServeBlob(c, blob); err != nil {
  48. c.ServerError("serve blob", err)
  49. return
  50. }
  51. }