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.

72 lines
2.0KB

  1. /* Package cache provides server-side caching capabilities with rich support of options and rules.
  2. Use it for server-side caching, see the `iris#Cache304` for an alternative approach that
  3. may fit your needs most.
  4. Example code:
  5. import (
  6. "time"
  7. "github.com/kataras/iris/v12"
  8. "github.com/kataras/iris/v12/cache"
  9. )
  10. func main(){
  11. app := iris.Default()
  12. middleware := cache.Handler(2 *time.Minute)
  13. app.Get("/hello", middleware, h)
  14. app.Listen(":8080")
  15. }
  16. func h(ctx iris.Context) {
  17. ctx.HTML("<h1> Hello, this should be cached. Every 2 minutes it will be refreshed, check your browser's inspector</h1>")
  18. }
  19. */
  20. package cache
  21. import (
  22. "time"
  23. "github.com/kataras/iris/v12/cache/client"
  24. "github.com/kataras/iris/v12/context"
  25. )
  26. // WithKey sets a custom entry key for cached pages.
  27. // Should be prepended to the cache handler.
  28. //
  29. // Usage:
  30. // app.Get("/", cache.WithKey("custom-key"), cache.Handler(time.Minute), mainHandler)
  31. func WithKey(key string) context.Handler {
  32. return func(ctx *context.Context) {
  33. client.SetKey(ctx, key)
  34. ctx.Next()
  35. }
  36. }
  37. // Cache accepts the cache expiration duration.
  38. // If the "expiration" input argument is invalid, <=2 seconds,
  39. // then expiration is taken by the "cache-control's maxage" header.
  40. // Returns a Handler structure which you can use to customize cache further.
  41. //
  42. // All types of response can be cached, templates, json, text, anything.
  43. //
  44. // Use it for server-side caching, see the `iris#Cache304` for an alternative approach that
  45. // may be more suited to your needs.
  46. //
  47. // You can add validators with this function.
  48. func Cache(expiration time.Duration) *client.Handler {
  49. return client.NewHandler(expiration)
  50. }
  51. // Handler like `Cache` but returns an Iris Handler to be used as a middleware.
  52. // For more options use the `Cache`.
  53. //
  54. // Examples can be found at: https://github.com/kataras/iris/tree/master/_examples/response-writer/cache
  55. func Handler(expiration time.Duration) context.Handler {
  56. h := Cache(expiration).ServeHTTP
  57. return h
  58. }