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
Copied!

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
)
Copied!
After you initiate your Fiber app, you can use the following possibilities:
1
// Initialize default config
2
app.Use(cache.New())
3
​
4
// Or extend your config for customization
5
app.Use(cache.New(cache.Config{
6
Next: func(c *fiber.Ctx) bool {
7
return c.Query("refresh") == "true"
8
},
9
Expiration: 30 * time.Minute,
10
CacheControl: true,
11
}))
Copied!
Or you can custom key and expire time like this:
1
app.Use(New(Config{
2
ExpirationGenerator: func(c *fiber.Ctx, cfg *Config) time.Duration {
3
newCacheTime, _ := strconv.Atoi(c.GetRespHeader("Cache-Time", "600"))
4
return time.Second * time.Duration(newCacheTime)
5
},
6
KeyGenerator: func(c *fiber.Ctx) string {
7
return c.Path()
8
}
9
}))
10
​
11
app.Get("/", func(c *fiber.Ctx) error {
12
c.Response().Header.Add("Cache-Time", "6000")
13
return c.SendString("hi")
14
})
Copied!

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
​
8
// Expiration is the time that an cached response will live
9
//
10
// Optional. Default: 1 * time.Minute
11
Expiration time.Duration
12
​
13
// CacheControl enables client side caching if set to true
14
//
15
// Optional. Default: false
16
CacheControl bool
17
​
18
// Key allows you to generate custom keys, by default c.Path() is used
19
//
20
// Default: func(c *fiber.Ctx) string {
21
// return utils.CopyString(c.Path())
22
// }
23
KeyGenerator func(*fiber.Ctx) string
24
25
// allows you to generate custom Expiration Key By Key, default is Expiration (Optional)
26
//
27
// Default: nil
28
ExpirationGenerator func(*fiber.Ctx, *Config) time.Duration
29
​
30
// Store is used to store the state of the middleware
31
//
32
// Default: an in memory store for this process only
33
Storage fiber.Storage
34
}
Copied!

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 utils.CopyString(c.Path())
8
},
9
ExpirationGenerator : nil,
10
Storage: nil,
11
}
Copied!
Last modified 10d ago