-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache.go
197 lines (176 loc) · 4.71 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
package gincache
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
"github.com/Pantani/errors"
"github.com/Pantani/logger"
"github.com/gin-gonic/gin"
"github.com/patrickmn/go-cache"
)
var (
memoryCache *memCache
)
func init() {
memoryCache = &memCache{cache: cache.New(5*time.Minute, 5*time.Minute)}
}
type memCache struct {
sync.RWMutex
cache *cache.Cache
}
type cacheResponse struct {
Status int
Header http.Header
Data []byte
}
type cachedWriter struct {
gin.ResponseWriter
status int
written bool
expire time.Duration
key string
}
var _ gin.ResponseWriter = &cachedWriter{}
// newCachedWriter create a new cache writer.
func newCachedWriter(expire time.Duration, writer gin.ResponseWriter, key string) *cachedWriter {
return &cachedWriter{writer, 0, false, expire, key}
}
// WriteHeader satisfy the built-in interface for writers.
func (w *cachedWriter) WriteHeader(code int) {
w.status = code
w.written = true
w.ResponseWriter.WriteHeader(code)
}
// Status satisfy the built-in interface for writers.
func (w *cachedWriter) Status() int {
return w.ResponseWriter.Status()
}
// Written satisfy the built-in interface for writers.
func (w *cachedWriter) Written() bool {
return w.ResponseWriter.Written()
}
// Write satisfy the built-in interface for writers.
func (w *cachedWriter) Write(data []byte) (int, error) {
ret, err := w.ResponseWriter.Write(data)
if err != nil {
return 0, errors.E(err, "fail to cache write string", errors.Params{"data": data})
}
if w.Status() != 200 {
return 0, errors.E("Write: invalid cache status", errors.Params{"data": data})
}
val := cacheResponse{
w.Status(),
w.Header(),
data,
}
b, err := json.Marshal(val)
if err != nil {
return 0, errors.E("validator cache: failed to marshal cache object")
}
memoryCache.cache.Set(w.key, b, w.expire)
return ret, nil
}
// WriteString satisfy the built-in interface for writers.
func (w *cachedWriter) WriteString(data string) (n int, err error) {
ret, err := w.ResponseWriter.WriteString(data)
if err != nil {
return 0, errors.E(err, "fail to cache write string", errors.Params{"data": data})
}
if w.Status() != 200 {
return 0, errors.E("WriteString: invalid cache status", errors.Params{"data": data})
}
val := cacheResponse{
w.Status(),
w.Header(),
[]byte(data),
}
b, err := json.Marshal(val)
if err != nil {
return 0, errors.E("validator cache: failed to marshal cache object")
}
memoryCache.setCache(w.key, b, w.expire)
return ret, err
}
// deleteCache remove cache from memory
func (mc *memCache) deleteCache(key string) {
mc.RLock()
defer mc.RUnlock()
memoryCache.cache.Delete(key)
}
// setCache save cache inside memory with duration.
func (mc *memCache) setCache(key string, data interface{}, d time.Duration) {
b, err := json.Marshal(data)
if err != nil {
logger.Error(errors.E(err, "client cache cannot marshal cache object"))
return
}
mc.RLock()
defer mc.RUnlock()
memoryCache.cache.Set(key, b, d)
}
// getCache restore cache from memory.
// It returns the cache and an error if occurs.
func (mc *memCache) getCache(key string) (cacheResponse, error) {
var result cacheResponse
c, ok := mc.cache.Get(key)
if !ok {
return result, fmt.Errorf("gin-cache: invalid cache key %s", key)
}
r, ok := c.([]byte)
if !ok {
return result, errors.E("validator cache: failed to cast cache to bytes")
}
err := json.Unmarshal(r, &result)
if err != nil {
return result, err
}
return result, nil
}
// generateKey generate a key to storage cache.
// It returns the key.
func generateKey(c *gin.Context) string {
url := c.Request.URL.String()
var b []byte
if c.Request.Body != nil {
b, _ = ioutil.ReadAll(c.Request.Body)
// Restore the io.ReadCloser to its original state
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(b))
}
hash := sha1.Sum(append([]byte(url), b...))
return base64.URLEncoding.EncodeToString(hash[:])
}
// CacheMiddleware encapsulates a gin handler function and caches the response with an expiration time.
// It returns the gin handler function.
func CacheMiddleware(expiration time.Duration, handle gin.HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
defer c.Next()
key := generateKey(c)
mc, err := memoryCache.getCache(key)
if err != nil || mc.Data == nil {
writer := newCachedWriter(expiration, c.Writer, key)
c.Writer = writer
handle(c)
if c.IsAborted() {
memoryCache.deleteCache(key)
}
return
}
c.Writer.WriteHeader(mc.Status)
for k, vals := range mc.Header {
for _, v := range vals {
c.Writer.Header().Set(k, v)
}
}
_, err = c.Writer.Write(mc.Data)
if err != nil {
memoryCache.deleteCache(key)
logger.Error(err, "cannot write data", mc)
}
}
}