forked from victorspringer/http-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
287 lines (241 loc) · 6.97 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*
MIT License
Copyright (c) 2018 Victor Springer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package cache
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"hash/fnv"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"sort"
"strconv"
"strings"
"time"
)
// Response is the cached response data structure.
type Response struct {
// Value is the cached response value.
Value []byte
// Header is the cached response header.
Header http.Header
// Expiration is the cached response expiration date.
Expiration time.Time
// LastAccess is the last date a cached response was accessed.
// Used by LRU and MRU algorithms.
LastAccess time.Time
// Frequency is the count of times a cached response is accessed.
// Used for LFU and MFU algorithms.
Frequency int
}
// Client data structure for HTTP cache middleware.
type Client struct {
adapter Adapter
ttl time.Duration
refreshKey string
methods []string
}
// ClientOption is used to set Client settings.
type ClientOption func(c *Client) error
// Adapter interface for HTTP cache middleware client.
type Adapter interface {
// Get retrieves the cached response by a given key. It also
// returns true or false, whether it exists or not.
Get(key uint64) ([]byte, bool)
// Set caches a response for a given key until an expiration date.
Set(key uint64, response []byte, expiration time.Time)
// Release frees cache for a given key.
Release(key uint64)
}
// Middleware is the HTTP cache middleware handler.
func (c *Client) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if c.cacheableMethod(r.Method) {
sortURLParams(r.URL)
key := generateKey(r.URL.String())
if r.Method == http.MethodPost && r.Body != nil {
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
next.ServeHTTP(w, r)
return
}
reader := ioutil.NopCloser(bytes.NewBuffer(body))
key = generateKeyWithBody(r.URL.String(), body)
r.Body = reader
}
params := r.URL.Query()
if _, ok := params[c.refreshKey]; ok {
delete(params, c.refreshKey)
r.URL.RawQuery = params.Encode()
key = generateKey(r.URL.String())
c.adapter.Release(key)
} else {
b, ok := c.adapter.Get(key)
response := BytesToResponse(b)
if ok {
if response.Expiration.After(time.Now()) {
response.LastAccess = time.Now()
response.Frequency++
c.adapter.Set(key, response.Bytes(), response.Expiration)
//w.WriteHeader(http.StatusNotModified)
for k, v := range response.Header {
w.Header().Set(k, strings.Join(v, ","))
}
w.Write(response.Value)
return
}
c.adapter.Release(key)
}
}
rec := httptest.NewRecorder()
next.ServeHTTP(rec, r)
result := rec.Result()
statusCode := result.StatusCode
value := rec.Body.Bytes()
if statusCode < 400 {
now := time.Now()
response := Response{
Value: value,
Header: result.Header,
Expiration: now.Add(c.ttl),
LastAccess: now,
Frequency: 1,
}
c.adapter.Set(key, response.Bytes(), response.Expiration)
}
for k, v := range result.Header {
w.Header().Set(k, strings.Join(v, ","))
}
w.WriteHeader(statusCode)
w.Write(value)
return
}
next.ServeHTTP(w, r)
})
}
func (c *Client) cacheableMethod(method string) bool {
for _, m := range c.methods {
if method == m {
return true
}
}
return false
}
// BytesToResponse converts bytes array into Response data structure.
func BytesToResponse(b []byte) Response {
var r Response
dec := gob.NewDecoder(bytes.NewReader(b))
dec.Decode(&r)
return r
}
// Bytes converts Response data structure into bytes array.
func (r Response) Bytes() []byte {
var b bytes.Buffer
enc := gob.NewEncoder(&b)
enc.Encode(&r)
return b.Bytes()
}
func sortURLParams(URL *url.URL) {
params := URL.Query()
for _, param := range params {
sort.Slice(param, func(i, j int) bool {
return param[i] < param[j]
})
}
URL.RawQuery = params.Encode()
}
// KeyAsString can be used by adapters to convert the cache key from uint64 to string.
func KeyAsString(key uint64) string {
return strconv.FormatUint(key, 36)
}
func generateKey(URL string) uint64 {
hash := fnv.New64a()
hash.Write([]byte(URL))
return hash.Sum64()
}
func generateKeyWithBody(URL string, body []byte) uint64 {
hash := fnv.New64a()
body = append([]byte(URL), body...)
hash.Write(body)
return hash.Sum64()
}
// NewClient initializes the cache HTTP middleware client with the given
// options.
func NewClient(opts ...ClientOption) (*Client, error) {
c := &Client{}
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, err
}
}
if c.adapter == nil {
return nil, errors.New("cache client adapter is not set")
}
if int64(c.ttl) < 1 {
return nil, errors.New("cache client ttl is not set")
}
if c.methods == nil {
c.methods = []string{http.MethodGet}
}
return c, nil
}
// ClientWithAdapter sets the adapter type for the HTTP cache
// middleware client.
func ClientWithAdapter(a Adapter) ClientOption {
return func(c *Client) error {
c.adapter = a
return nil
}
}
// ClientWithTTL sets how long each response is going to be cached.
func ClientWithTTL(ttl time.Duration) ClientOption {
return func(c *Client) error {
if int64(ttl) < 1 {
return fmt.Errorf("cache client ttl %v is invalid", ttl)
}
c.ttl = ttl
return nil
}
}
// ClientWithRefreshKey sets the parameter key used to free a request
// cached response. Optional setting.
func ClientWithRefreshKey(refreshKey string) ClientOption {
return func(c *Client) error {
c.refreshKey = refreshKey
return nil
}
}
// ClientWithMethods sets the acceptable HTTP methods to be cached.
// Optional setting. If not set, default is "GET".
func ClientWithMethods(methods []string) ClientOption {
return func(c *Client) error {
for _, method := range methods {
if method != http.MethodGet && method != http.MethodPost {
return fmt.Errorf("invalid method %s", method)
}
}
c.methods = methods
return nil
}
}