-
Notifications
You must be signed in to change notification settings - Fork 13
/
cache.go
171 lines (140 loc) · 3.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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// Package plugin_simplecache is a plugin to cache responses to disk.
package plugin_simplecache
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
"time"
"github.com/pquerna/cachecontrol"
)
// Config configures the middleware.
type Config struct {
Path string `json:"path" yaml:"path" toml:"path"`
MaxExpiry int `json:"maxExpiry" yaml:"maxExpiry" toml:"maxExpiry"`
Cleanup int `json:"cleanup" yaml:"cleanup" toml:"cleanup"`
AddStatusHeader bool `json:"addStatusHeader" yaml:"addStatusHeader" toml:"addStatusHeader"`
}
// CreateConfig returns a config instance.
func CreateConfig() *Config {
return &Config{
MaxExpiry: int((5 * time.Minute).Seconds()),
Cleanup: int((5 * time.Minute).Seconds()),
AddStatusHeader: true,
}
}
const (
cacheHeader = "Cache-Status"
cacheHitStatus = "hit"
cacheMissStatus = "miss"
cacheErrorStatus = "error"
)
type cache struct {
name string
cache *fileCache
cfg *Config
next http.Handler
}
// New returns a plugin instance.
func New(_ context.Context, next http.Handler, cfg *Config, name string) (http.Handler, error) {
if cfg.MaxExpiry <= 1 {
return nil, errors.New("maxExpiry must be greater or equal to 1")
}
if cfg.Cleanup <= 1 {
return nil, errors.New("cleanup must be greater or equal to 1")
}
fc, err := newFileCache(cfg.Path, time.Duration(cfg.Cleanup)*time.Second)
if err != nil {
return nil, err
}
m := &cache{
name: name,
cache: fc,
cfg: cfg,
next: next,
}
return m, nil
}
type cacheData struct {
Status int
Headers map[string][]string
Body []byte
}
// ServeHTTP serves an HTTP request.
func (m *cache) ServeHTTP(w http.ResponseWriter, r *http.Request) {
cs := cacheMissStatus
key := cacheKey(r)
b, err := m.cache.Get(key)
if err == nil {
var data cacheData
err := json.Unmarshal(b, &data)
if err != nil {
cs = cacheErrorStatus
} else {
for key, vals := range data.Headers {
for _, val := range vals {
w.Header().Add(key, val)
}
}
if m.cfg.AddStatusHeader {
w.Header().Set(cacheHeader, cacheHitStatus)
}
w.WriteHeader(data.Status)
_, _ = w.Write(data.Body)
return
}
}
if m.cfg.AddStatusHeader {
w.Header().Set(cacheHeader, cs)
}
rw := &responseWriter{ResponseWriter: w}
m.next.ServeHTTP(rw, r)
expiry, ok := m.cacheable(r, w, rw.status)
if !ok {
return
}
data := cacheData{
Status: rw.status,
Headers: w.Header(),
Body: rw.body,
}
b, err = json.Marshal(data)
if err != nil {
log.Printf("Error serializing cache item: %v", err)
}
if err = m.cache.Set(key, b, expiry); err != nil {
log.Printf("Error setting cache item: %v", err)
}
}
func (m *cache) cacheable(r *http.Request, w http.ResponseWriter, status int) (time.Duration, bool) {
reasons, expireBy, err := cachecontrol.CachableResponseWriter(r, status, w, cachecontrol.Options{})
if err != nil || len(reasons) > 0 {
return 0, false
}
expiry := time.Until(expireBy)
maxExpiry := time.Duration(m.cfg.MaxExpiry) * time.Second
if maxExpiry < expiry {
expiry = maxExpiry
}
return expiry, true
}
func cacheKey(r *http.Request) string {
return r.Method + r.Host + r.URL.Path
}
type responseWriter struct {
http.ResponseWriter
status int
body []byte
}
func (rw *responseWriter) Header() http.Header {
return rw.ResponseWriter.Header()
}
func (rw *responseWriter) Write(p []byte) (int, error) {
rw.body = append(rw.body, p...)
return rw.ResponseWriter.Write(p)
}
func (rw *responseWriter) WriteHeader(s int) {
rw.status = s
rw.ResponseWriter.WriteHeader(s)
}