This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cacheman.go
82 lines (65 loc) · 1.47 KB
/
cacheman.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package cacheman
import (
"fmt"
"strings"
"github.com/aofei/air"
)
// GasConfig is a set of configurations for the `Gas`.
type GasConfig struct {
MustRevalidate bool
NoCache bool
NoStore bool
NoTransform bool
Public bool
Private bool
ProxyRevalidate bool
MaxAge int
SMaxAge int
Skippable func(*air.Request, *air.Response) bool
}
// Gas returns an `air.Gas` that is used to manage the Cache-Control header
// based on the gc.
func Gas(gc GasConfig) air.Gas {
ds := []string{}
if gc.MustRevalidate {
ds = append(ds, "must-revalidate")
}
if gc.NoCache {
ds = append(ds, "no-cache")
}
if gc.NoStore {
ds = append(ds, "no-store")
}
if gc.NoTransform {
ds = append(ds, "no-transform")
}
if gc.Public {
ds = append(ds, "public")
}
if gc.Private {
ds = append(ds, "private")
}
if gc.ProxyRevalidate {
ds = append(ds, "proxy-revalidate")
}
if gc.MaxAge >= 0 {
ds = append(ds, fmt.Sprintf("max-age=%d", gc.MaxAge))
}
if gc.SMaxAge >= 0 {
ds = append(ds, fmt.Sprintf("s-maxage=%d", gc.SMaxAge))
}
directives := strings.Join(ds, ", ")
return func(next air.Handler) air.Handler {
return func(req *air.Request, res *air.Response) error {
if gc.Skippable != nil && gc.Skippable(req, res) {
return next(req, res)
}
res.Header.Set("Cache-Control", directives)
err := next(req, res)
if err != nil && !res.Written {
res.Header.Del("Cache-Control")
}
return err
}
}
}