gitea源码

serve.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package common
  4. import (
  5. "io"
  6. "path"
  7. "time"
  8. repo_model "code.gitea.io/gitea/models/repo"
  9. "code.gitea.io/gitea/modules/git"
  10. "code.gitea.io/gitea/modules/httpcache"
  11. "code.gitea.io/gitea/modules/httplib"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/structs"
  15. "code.gitea.io/gitea/services/context"
  16. )
  17. // ServeBlob download a git.Blob
  18. func ServeBlob(ctx *context.Base, repo *repo_model.Repository, filePath string, blob *git.Blob, lastModified *time.Time) error {
  19. if httpcache.HandleGenericETagTimeCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
  20. return nil
  21. }
  22. dataRc, err := blob.DataAsync()
  23. if err != nil {
  24. return err
  25. }
  26. defer func() {
  27. if err = dataRc.Close(); err != nil {
  28. log.Error("ServeBlob: Close: %v", err)
  29. }
  30. }()
  31. _ = repo.LoadOwner(ctx)
  32. httplib.ServeContentByReader(ctx.Req, ctx.Resp, blob.Size(), dataRc, &httplib.ServeHeaderOptions{
  33. Filename: path.Base(filePath),
  34. CacheIsPublic: !repo.IsPrivate && repo.Owner != nil && repo.Owner.Visibility == structs.VisibleTypePublic,
  35. CacheDuration: setting.StaticCacheTime,
  36. })
  37. return nil
  38. }
  39. func ServeContentByReader(ctx *context.Base, filePath string, size int64, reader io.Reader) {
  40. httplib.ServeContentByReader(ctx.Req, ctx.Resp, size, reader, &httplib.ServeHeaderOptions{Filename: path.Base(filePath)})
  41. }
  42. func ServeContentByReadSeeker(ctx *context.Base, filePath string, modTime *time.Time, reader io.ReadSeeker) {
  43. httplib.ServeContentByReadSeeker(ctx.Req, ctx.Resp, modTime, reader, &httplib.ServeHeaderOptions{Filename: path.Base(filePath)})
  44. }