forked from OneOfOne/gserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
79 lines (66 loc) · 1.53 KB
/
cache.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
package gserv
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/alpineiq/genh"
)
type cacheItem struct {
value Response
headers http.Header
created int64
}
type cacheMap = genh.LMap[string, *cacheItem]
func cleanCache(m *cacheMap, ttl int64) {
for {
now := time.Now().Unix()
m.Update(func(m map[string]*cacheItem) {
for k, it := range m {
if now > it.created+ttl {
delete(m, k)
}
}
})
time.Sleep(time.Second * time.Duration(ttl))
}
}
func CacheHandler(etag func(ctx *Context) string, ttlDuration time.Duration, handler Handler) Handler {
c := cacheMap{}
ttl := int64(ttlDuration.Seconds())
if ttlDuration > 0 {
go cleanCache(&c, ttl)
}
maxAge := "max-age=" + strconv.FormatInt(ttl, 10)
return func(ctx *Context) Response {
if ct := ctx.ReqHeader("Cache-Control"); strings.Contains(ct, "no-cache") || strings.Contains(ct, "max-age=0") {
return handler(ctx)
}
tag := etag(ctx)
if tag == "-" || tag == "" {
return handler(ctx)
}
if _, ok := ctx.ResponseWriter.(*gzipRW); !ok {
// less likely to trigger
tag += ":0"
}
it := c.MustGet(tag, func() *cacheItem {
resp := handler(ctx)
if cr, ok := resp.(CacheableResponse); ok {
resp = cr.Cached()
}
return &cacheItem{
created: time.Now().Unix(),
headers: ctx.Header(),
value: resp,
}
})
h := ctx.Header()
for k, v := range it.headers {
h[k] = v
}
h.Set("Last-Modified", time.Unix(it.created, 0).UTC().Format(time.RFC1123))
h.Set("Cache-Control", maxAge)
return it.value
}
}