You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

httpcache.go 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. // Copyright 2020 The Gitea 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 httpcache
  5. import (
  6. "encoding/base64"
  7. "fmt"
  8. "net/http"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/modules/setting"
  14. )
  15. // AddCacheControlToHeader adds suitable cache-control headers to response
  16. func AddCacheControlToHeader(h http.Header, maxAge time.Duration, additionalDirectives ...string) {
  17. directives := make([]string, 0, 2+len(additionalDirectives))
  18. if setting.IsProd {
  19. if maxAge == 0 {
  20. directives = append(directives, "no-store")
  21. } else {
  22. directives = append(directives, "private", "max-age="+strconv.Itoa(int(maxAge.Seconds())))
  23. }
  24. } else {
  25. directives = append(directives, "no-store")
  26. // to remind users they are using non-prod setting.
  27. h.Add("X-Gitea-Debug", "RUN_MODE="+setting.RunMode)
  28. }
  29. h.Set("Cache-Control", strings.Join(append(directives, additionalDirectives...), ", "))
  30. }
  31. // generateETag generates an ETag based on size, filename and file modification time
  32. func generateETag(fi os.FileInfo) string {
  33. etag := fmt.Sprint(fi.Size()) + fi.Name() + fi.ModTime().UTC().Format(http.TimeFormat)
  34. return `"` + base64.StdEncoding.EncodeToString([]byte(etag)) + `"`
  35. }
  36. // HandleTimeCache handles time-based caching for a HTTP request
  37. func HandleTimeCache(req *http.Request, w http.ResponseWriter, fi os.FileInfo) (handled bool) {
  38. return HandleGenericTimeCache(req, w, fi.ModTime())
  39. }
  40. // HandleGenericTimeCache handles time-based caching for a HTTP request
  41. func HandleGenericTimeCache(req *http.Request, w http.ResponseWriter, lastModified time.Time) (handled bool) {
  42. AddCacheControlToHeader(w.Header(), setting.StaticCacheTime)
  43. ifModifiedSince := req.Header.Get("If-Modified-Since")
  44. if ifModifiedSince != "" {
  45. t, err := time.Parse(http.TimeFormat, ifModifiedSince)
  46. if err == nil && lastModified.Unix() <= t.Unix() {
  47. w.WriteHeader(http.StatusNotModified)
  48. return true
  49. }
  50. }
  51. w.Header().Set("Last-Modified", lastModified.Format(http.TimeFormat))
  52. return false
  53. }
  54. // HandleFileETagCache handles ETag-based caching for a HTTP request
  55. func HandleFileETagCache(req *http.Request, w http.ResponseWriter, fi os.FileInfo) (handled bool) {
  56. etag := generateETag(fi)
  57. return HandleGenericETagCache(req, w, etag)
  58. }
  59. // HandleGenericETagCache handles ETag-based caching for a HTTP request.
  60. // It returns true if the request was handled.
  61. func HandleGenericETagCache(req *http.Request, w http.ResponseWriter, etag string) (handled bool) {
  62. if len(etag) > 0 {
  63. w.Header().Set("Etag", etag)
  64. if checkIfNoneMatchIsValid(req, etag) {
  65. w.WriteHeader(http.StatusNotModified)
  66. return true
  67. }
  68. }
  69. AddCacheControlToHeader(w.Header(), setting.StaticCacheTime)
  70. return false
  71. }
  72. // checkIfNoneMatchIsValid tests if the header If-None-Match matches the ETag
  73. func checkIfNoneMatchIsValid(req *http.Request, etag string) bool {
  74. ifNoneMatch := req.Header.Get("If-None-Match")
  75. if len(ifNoneMatch) > 0 {
  76. for _, item := range strings.Split(ifNoneMatch, ",") {
  77. item = strings.TrimSpace(item)
  78. if item == etag {
  79. return true
  80. }
  81. }
  82. }
  83. return false
  84. }
  85. // HandleGenericETagTimeCache handles ETag-based caching with Last-Modified caching for a HTTP request.
  86. // It returns true if the request was handled.
  87. func HandleGenericETagTimeCache(req *http.Request, w http.ResponseWriter, etag string, lastModified time.Time) (handled bool) {
  88. if len(etag) > 0 {
  89. w.Header().Set("Etag", etag)
  90. }
  91. if !lastModified.IsZero() {
  92. w.Header().Set("Last-Modified", lastModified.Format(http.TimeFormat))
  93. }
  94. if len(etag) > 0 {
  95. if checkIfNoneMatchIsValid(req, etag) {
  96. w.WriteHeader(http.StatusNotModified)
  97. return true
  98. }
  99. }
  100. if !lastModified.IsZero() {
  101. ifModifiedSince := req.Header.Get("If-Modified-Since")
  102. if ifModifiedSince != "" {
  103. t, err := time.Parse(http.TimeFormat, ifModifiedSince)
  104. if err == nil && lastModified.Unix() <= t.Unix() {
  105. w.WriteHeader(http.StatusNotModified)
  106. return true
  107. }
  108. }
  109. }
  110. AddCacheControlToHeader(w.Header(), setting.StaticCacheTime)
  111. return false
  112. }