download.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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/modules/base"
  10. "github.com/gogits/gogs/modules/context"
  11. "github.com/gogits/gogs/modules/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 !base.IsTextFile(buf) {
  20. if !base.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. }