-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
145 lines (122 loc) · 3.34 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
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
package httpcache
import (
"fmt"
"hash/fnv"
"net/http"
"net/url"
"strings"
"time"
lru "github.com/hashicorp/golang-lru"
)
var cachableVerbs = map[string]interface{} {
http.MethodGet: struct{}{},
http.MethodOptions: struct{}{},
http.MethodHead: struct{}{},
}
type httpResponseEntry struct {
Body []byte
Code int
Header http.Header
Created time.Time
}
// A HttpCache is a caching middleware.
type HttpCache struct {
cache *lru.ARCCache
allowedVerbs map[string]interface{}
maxAge int64
}
// Options a configuration container for `httpcache` middleware.
type Options struct {
// AllowedVerbs is the list of HTTP Verbs that allowed for caching.
// Supported cachable verbs: GET, HEAD, OPTIONS.
// All supported verbs are allowed by http.
AllowedVerbs []string
// MaxAge is the maximum age in milliseconds response entry remains in cache.
// Default value is 60000 milliseconds.
MaxAge int64
// Size is the initial capacity of cache.
// Default value is 1000.
Size int
}
// New creates a new instance of `httpcache` middleware.
func New(options *Options) *HttpCache {
c, err := lru.NewARC(options.Size)
if err != nil {
panic(fmt.Errorf("unable to initialize cache: %v", err))
}
httpCache := &HttpCache{cache: c, maxAge: options.MaxAge, allowedVerbs: make(map[string]interface{})}
for _, verb := range options.AllowedVerbs {
if _, cachableVerb := cachableVerbs[verb]; cachableVerb {
if _, ok := httpCache.allowedVerbs[verb]; !ok {
httpCache.allowedVerbs[verb] = struct{}{}
}
}
}
return httpCache
}
// NewDefault creates a new instance of `http-cache` middleware with default Options.
func NewDefault() *HttpCache {
return New(&Options{
Size: 1000,
MaxAge: 60000,
AllowedVerbs: []string{
http.MethodGet,
http.MethodHead,
http.MethodOptions,
}})
}
// Handler adds caching on the request if its HTTP verb is supported.
func (c *HttpCache) Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
c.ServeHTTP(w, r, h.ServeHTTP)
})
}
// ServeHTTP is a Negroni middleware compatible interface.
func (c *HttpCache) ServeHTTP(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
// Skip non-cachable HTTP verbs.
if _, ok := c.allowedVerbs[req.Method]; ok {
setHeader := func(header http.Header){
for k, v := range header{
rw.Header().Set(k, strings.Join(v, ";"))
}
}
key, err := cacheKey(req.URL)
if err != nil {
panic(err)
}
if c.cache.Contains(key) {
if respEntry, ok := c.cache.Get(key); ok {
resp := respEntry.(httpResponseEntry)
// Validate cache entry MaxAge.
if time.Now().Sub(resp.Created).Milliseconds() <= c.maxAge {
setHeader(resp.Header)
rw.WriteHeader(resp.Code)
_, err := rw.Write(resp.Body)
if err != nil {
panic(err)
}
return
}
}
}
rrw := NewResponseRecorder()
next(rrw, req)
c.cache.Add(key, httpResponseEntry{Code: rrw.Code(), Header: rrw.Result().Header, Body: rrw.Body().Bytes(), Created: time.Now()})
setHeader(rrw.Result().Header)
rw.WriteHeader(rrw.Code())
_, err = rw.Write(rrw.Body().Bytes())
if err != nil {
panic(err)
}
} else {
next(rw, req)
}
}
func cacheKey(u *url.URL) (string, error) {
hash := fnv.New128a()
_, err := hash.Write([]byte(u.String()))
if err != nil {
return "", err
}
return string(hash.Sum(nil)), nil
}