-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache-control.go
59 lines (50 loc) · 1.14 KB
/
cache-control.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package middleware
import (
"fmt"
"time"
"github.com/go-zoox/core-utils/regexp"
"github.com/go-zoox/headers"
"github.com/go-zoox/zoox"
)
// CacheControlConfig ...
type CacheControlConfig struct {
Paths []string
MaxAge time.Duration
//
Items []*CacheControlItem
}
// CacheControlItem ...
type CacheControlItem struct {
Path regexp.RegExp
MaxAge time.Duration
}
// CacheControl is a middleware that adds a "Cache-Control" header to the request.
func CacheControl(cfg *CacheControlConfig) zoox.Middleware {
for _, path := range cfg.Paths {
re, err := regexp.New(path)
if err != nil {
panic(err)
}
cfg.Items = append(cfg.Items, &CacheControlItem{
Path: re,
MaxAge: cfg.MaxAge,
})
}
return func(ctx *zoox.Context) {
if ctx.Method != "GET" {
ctx.Next()
return
}
if cfg.Items != nil {
for _, item := range cfg.Items {
if item.Path.Match(ctx.Path) {
maxAge := cfg.MaxAge / time.Second
// ctx.Logger.Infof("[middleware][cache-control] hit path: %s, max-age: %d", ctx.Path, maxAge)
ctx.Set(headers.CacheControl, fmt.Sprintf("public, max-age=%d", maxAge))
break
}
}
}
ctx.Next()
}
}