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.2KB

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