download.go 1.5 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(ctx *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. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"")
  22. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  23. }
  24. } else if !setting.Repository.EnableRawFileRenderMode || !ctx.QueryBool("render") {
  25. ctx.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
  26. }
  27. ctx.Resp.Write(buf)
  28. _, err := io.Copy(ctx.Resp, reader)
  29. return err
  30. }
  31. func ServeBlob(ctx *context.Context, blob *git.Blob) error {
  32. dataRc, err := blob.Data()
  33. if err != nil {
  34. return err
  35. }
  36. return ServeData(ctx, path.Base(ctx.Repo.TreePath), dataRc)
  37. }
  38. func SingleDownload(ctx *context.Context) {
  39. blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreePath)
  40. if err != nil {
  41. if git.IsErrNotExist(err) {
  42. ctx.Handle(404, "GetBlobByPath", nil)
  43. } else {
  44. ctx.Handle(500, "GetBlobByPath", err)
  45. }
  46. return
  47. }
  48. if err = ServeBlob(ctx, blob); err != nil {
  49. ctx.Handle(500, "ServeBlob", err)
  50. }
  51. }