browser.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. package cache
  2. import (
  3. "strconv"
  4. "time"
  5. "github.com/kataras/iris/v12/cache/client"
  6. "github.com/kataras/iris/v12/context"
  7. )
  8. // CacheControlHeaderValue is the header value of the
  9. // "Cache-Control": "private, no-cache, max-age=0, must-revalidate, no-store, proxy-revalidate, s-maxage=0".
  10. //
  11. // It can be overridden.
  12. var CacheControlHeaderValue = "private, no-cache, max-age=0, must-revalidate, no-store, proxy-revalidate, s-maxage=0"
  13. const (
  14. // PragmaHeaderKey is the header key of "Pragma".
  15. PragmaHeaderKey = "Pragma"
  16. // PragmaNoCacheHeaderValue is the header value of "Pragma": "no-cache".
  17. PragmaNoCacheHeaderValue = "no-cache"
  18. // ExpiresHeaderKey is the header key of "Expires".
  19. ExpiresHeaderKey = "Expires"
  20. // ExpiresNeverHeaderValue is the header value of "ExpiresHeaderKey": "0".
  21. ExpiresNeverHeaderValue = "0"
  22. )
  23. // NoCache is a middleware which overrides the Cache-Control, Pragma and Expires headers
  24. // in order to disable the cache during the browser's back and forward feature.
  25. //
  26. // A good use of this middleware is on HTML routes; to refresh the page even on "back" and "forward" browser's arrow buttons.
  27. //
  28. // See `cache#StaticCache` for the opposite behavior.
  29. var NoCache = func(ctx *context.Context) {
  30. ctx.Header(context.CacheControlHeaderKey, CacheControlHeaderValue)
  31. ctx.Header(PragmaHeaderKey, PragmaNoCacheHeaderValue)
  32. ctx.Header(ExpiresHeaderKey, ExpiresNeverHeaderValue)
  33. // Add the X-No-Cache header as well, for any customized case, i.e `cache#Handler` or `cache#Cache`.
  34. client.NoCache(ctx)
  35. ctx.Next()
  36. }
  37. // StaticCache middleware for caching static files by sending the "Cache-Control" and "Expires" headers to the client.
  38. // It accepts a single input parameter, the "cacheDur", a time.Duration that it's used to calculate the expiration.
  39. //
  40. // If "cacheDur" <=0 then it returns the `NoCache` middleware instaed to disable the caching between browser's "back" and "forward" actions.
  41. //
  42. // Usage: `app.Use(cache.StaticCache(24 * time.Hour))` or `app.Use(cache.Staticcache(-1))`.
  43. // A middleware, which is a simple Handler can be called inside another handler as well, example:
  44. // cacheMiddleware := cache.StaticCache(...)
  45. //
  46. // func(ctx iris.Context){
  47. // cacheMiddleware(ctx)
  48. // [...]
  49. // }
  50. var StaticCache = func(cacheDur time.Duration) context.Handler {
  51. if int64(cacheDur) <= 0 {
  52. return NoCache
  53. }
  54. cacheControlHeaderValue := "public, max-age=" + strconv.Itoa(int(cacheDur.Seconds()))
  55. return func(ctx *context.Context) {
  56. cacheUntil := time.Now().Add(cacheDur).Format(ctx.Application().ConfigurationReadOnly().GetTimeFormat())
  57. ctx.Header(ExpiresHeaderKey, cacheUntil)
  58. ctx.Header(context.CacheControlHeaderKey, cacheControlHeaderValue)
  59. ctx.Next()
  60. }
  61. }
  62. const ifNoneMatchHeaderKey = "If-None-Match"
  63. // ETag is another browser & server cache request-response feature.
  64. // It can be used side by side with the `StaticCache`, usually `StaticCache` middleware should go first.
  65. // This should be used on routes that serves static files only.
  66. // The key of the `ETag` is the `ctx.Request().URL.Path`, invalidation of the not modified cache method
  67. // can be made by other request handler as well.
  68. //
  69. // In typical usage, when a URL is retrieved, the web server will return the resource's current
  70. // representation along with its corresponding ETag value,
  71. // which is placed in an HTTP response header "ETag" field:
  72. //
  73. // ETag: "/mypath"
  74. //
  75. // The client may then decide to cache the representation, along with its ETag.
  76. // Later, if the client wants to retrieve the same URL resource again,
  77. // it will first determine whether the local cached version of the URL has expired
  78. // (through the Cache-Control (`StaticCache` method) and the Expire headers).
  79. // If the URL has not expired, it will retrieve the local cached resource.
  80. // If it determined that the URL has expired (is stale), then the client will contact the server
  81. // and send its previously saved copy of the ETag along with the request in a "If-None-Match" field.
  82. //
  83. // Usage with combination of `StaticCache`:
  84. // assets := app.Party("/assets", cache.StaticCache(24 * time.Hour), ETag)
  85. // assets.HandleDir("/", iris.Dir("./assets"))
  86. //
  87. // Similar to `Cache304` but it doesn't depends on any "modified date", it uses just the ETag and If-None-Match headers.
  88. //
  89. // Read more at: https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching and
  90. // https://en.wikipedia.org/wiki/HTTP_ETag
  91. var ETag = func(ctx *context.Context) {
  92. key := ctx.Request().URL.Path
  93. ctx.Header(context.ETagHeaderKey, key)
  94. if match := ctx.GetHeader(ifNoneMatchHeaderKey); match == key {
  95. ctx.WriteNotModified()
  96. return
  97. }
  98. ctx.Next()
  99. }
  100. // Cache304 sends a `StatusNotModified` (304) whenever
  101. // the "If-Modified-Since" request header (time) is before the
  102. // time.Now() + expiresEvery (always compared to their UTC values).
  103. // Use this `cache#Cache304` instead of the "github.com/kataras/iris/v12/cache" or iris.Cache
  104. // for better performance.
  105. // Clients that are compatible with the http RCF (all browsers are and tools like postman)
  106. // will handle the caching.
  107. // The only disadvantage of using that instead of server-side caching
  108. // is that this method will send a 304 status code instead of 200,
  109. // So, if you use it side by side with other micro services
  110. // you have to check for that status code as well for a valid response.
  111. //
  112. // Developers are free to extend this method's behavior
  113. // by watching system directories changes manually and use of the `ctx.WriteWithExpiration`
  114. // with a "modtime" based on the file modified date,
  115. // can be used on Party's that contains a static handler,
  116. // i.e `HandleDir`.
  117. var Cache304 = func(expiresEvery time.Duration) context.Handler {
  118. return func(ctx *context.Context) {
  119. now := time.Now()
  120. if modified, err := ctx.CheckIfModifiedSince(now.Add(-expiresEvery)); !modified && err == nil {
  121. ctx.WriteNotModified()
  122. return
  123. }
  124. ctx.SetLastModified(now)
  125. ctx.Next()
  126. }
  127. }