forked from gramework/gramework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_cache.go
More file actions
152 lines (127 loc) · 3.86 KB
/
app_cache.go
File metadata and controls
152 lines (127 loc) · 3.86 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// +build cache
package gramework
import (
"errors"
"time"
"github.com/VictoriaMetrics/fastcache"
)
func (opts *CacheOptions) validate() error {
if opts.TTL <= 0 {
return errors.New("TTL must be grater than 0")
}
if opts.CacheKey == nil {
opts.CacheKey = defaultCacheOpts.CacheKey
}
if opts.Cacheable == nil {
opts.Cacheable = defaultCacheOpts.Cacheable
}
return nil
}
var defaultCacheOpts = NewCacheOptions()
// NewCacheOptions returns a cache options with default settings.
func NewCacheOptions() *CacheOptions {
return &CacheOptions{
TTL: 30 * time.Second,
Cacheable: func(ctx *Context) bool {
if len(ctx.Request.Header.Peek("Authentication")) > 0 {
return false
}
if len(ctx.Cookies.Storage) > 0 {
return false
}
return true
},
CacheKey: func(ctx *Context) []byte {
return ctx.Path()
},
}
}
// CacheFor is a shortcut to set ttl easily. See app.Cache() for docs.
func (app *App) CacheFor(handler interface{}, ttl time.Duration) func(ctx *Context) {
opts := app.getCacheOpts()
opts.TTL = ttl
return app.Cache(handler, opts)
}
// Cache wrapper will cache given handler using provided options. If options parameter omitted,
// this function will use default options.
//
// NOTE: Please, your CacheOptions' TTL must be more than 0.
func (app *App) Cache(handler interface{}, options ...*CacheOptions) func(ctx *Context) {
opts := app.getCacheOpts(options...)
if err := opts.validate(); err != nil {
app.Logger.WithError(err).Fatal("could not initialize cache middleware: check options")
}
wrappedHandler := app.defaultRouter.determineHandler(handler)
if opts.ReadCache == nil || opts.StoreCache == nil {
cache := fastcache.New(1)
opts.ReadCache = readFastCache(cache)
opts.StoreCache = storeFastCache(cache)
}
return func(ctx *Context) {
if opts.Cacheable(ctx) {
cacheKey := opts.CacheKey(ctx)
if value, isValid := opts.ReadCache(ctx, cacheKey); isValid {
serializedHeaders, isValid := opts.ReadCache(ctx, append(cacheKey, []byte("-headers")...))
if isValid {
headers := map[string]string{}
err := json.Unmarshal(serializedHeaders, &headers)
if err == nil {
for name, value := range headers {
ctx.Response.Header.Set(name, value)
}
ctx.Response.SetBody(value)
return
}
}
}
wrappedHandler(ctx)
b := ctx.Response.Body()
opts.StoreCache(ctx, cacheKey, b, opts.TTL)
headers, ok := serializeHeaders(ctx, opts)
if ok {
opts.StoreCache(ctx, append(cacheKey, []byte("-headers")...), headers, opts.TTL)
}
return
}
wrappedHandler(ctx)
}
}
func serializeHeaders(ctx *Context, opts *CacheOptions) ([]byte, bool) {
headers := map[string]string{
"Content-Type": string(ctx.Response.Header.Peek("Content-Type")),
"Content-Length": string(ctx.Response.Header.Peek("Content-Length")),
}
for _, header := range opts.CacheableHeaders {
headers[header] = string(ctx.Response.Header.Peek(header))
}
for _, header := range opts.NonCacheableHeaders {
delete(headers, header)
}
serialized, err := json.Marshal(headers)
return serialized, err == nil
}
func readFastCache(cache *fastcache.Cache) func(_ *Context, key []byte) (value []byte, isValid bool) {
return func(_ *Context, key []byte) ([]byte, bool) {
return cache.GetWithTimeout(nil, key)
}
}
func storeFastCache(cache *fastcache.Cache) func(_ *Context, key, value []byte, ttl time.Duration) {
return func(_ *Context, key, value []byte, ttl time.Duration) {
cache.SetWithTimeout(key, value, ttl)
}
}
func (app *App) getCacheOpts(options ...*CacheOptions) *CacheOptions {
opts := defaultCacheOpts
switch {
case len(options) > 1:
app.Logger.Warn("got more than one set of cache options: using the first one.")
fallthrough
case len(options) == 1:
if options[0] != nil {
opts = options[0]
}
case app.DefaultCacheOptions != nil:
opts = app.DefaultCacheOptions
}
return opts
}