Cache

Cache middleware for Fiber designed to intercept responses and cache them. This middleware will cache the Body, Content-Type and StatusCode using the c.Path() as unique identifier. Special thanks to @codemicro for creating this middleware for Fiber core!

Table of Contents

Signatures

  1. func New(config ...Config) fiber.Handler

Examples

Import the middleware package that is part of the Fiber web framework

  1. import (
  2. "github.com/gofiber/fiber/v2"
  3. "github.com/gofiber/fiber/v2/middleware/cache"
  4. )

After you initiate your Fiber app, you can use the following possibilities:

  1. // Initialize default config
  2. app.Use(cache.New())
  3. // Or extend your config for customization
  4. app.Use(cache.New(cache.Config{
  5. Next: func(c *fiber.Ctx) bool {
  6. return c.Query("refresh") == "true"
  7. },
  8. Expiration: 30 * time.Minute,
  9. CacheControl: true,
  10. }))

Config

  1. // Config defines the config for middleware.
  2. type Config struct {
  3. // Next defines a function to skip this middleware when returned true.
  4. //
  5. // Optional. Default: nil
  6. Next func(c *fiber.Ctx) bool
  7. // Expiration is the time that an cached response will live
  8. //
  9. // Optional. Default: 1 * time.Minute
  10. Expiration time.Duration
  11. // CacheControl enables client side caching if set to true
  12. //
  13. // Optional. Default: false
  14. CacheControl bool
  15. // Key allows you to generate custom keys, by default c.Path() is used
  16. //
  17. // Default: func(c *fiber.Ctx) string {
  18. // return c.Path()
  19. // }
  20. KeyGenerator func(*fiber.Ctx) string
  21. // Store is used to store the state of the middleware
  22. //
  23. // Default: an in memory store for this process only
  24. Storage fiber.Storage
  25. }

Default Config

  1. // ConfigDefault is the default config
  2. var ConfigDefault = Config{
  3. Next: nil,
  4. Expiration: 1 * time.Minute,
  5. CacheControl: false,
  6. KeyGenerator: func(c *fiber.Ctx) string {
  7. return c.Path()
  8. },
  9. Storage: nil,
  10. }