This repository has been archived by the owner on Nov 12, 2024. It is now read-only.
forked from coty91/cache
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcache.go
243 lines (218 loc) · 5.44 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
package cache
import (
"bytes"
"crypto/sha1"
"encoding/gob"
"io"
"log"
"net/http"
"net/url"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/stockx/go-gin-cache/persistence"
)
const (
CACHE_MIDDLEWARE_KEY = "gincontrib.cache"
)
var (
PageCachePrefix = "gincontrib.page.cache"
)
type responseCache struct {
Status int
Header http.Header
Data []byte
}
// RegisterResponseCacheGob registers the responseCache type with the encoding/gob package
func RegisterResponseCacheGob() {
gob.Register(responseCache{})
}
type cachedWriter struct {
gin.ResponseWriter
status int
written bool
store persistence.CacheStore
expire time.Duration
key string
}
var _ gin.ResponseWriter = &cachedWriter{}
// CreateKey creates a package specific key for a given string
func CreateKey(u string) string {
return urlEscape(PageCachePrefix, u)
}
func urlEscape(prefix string, u string) string {
key := url.QueryEscape(u)
if len(key) > 200 {
h := sha1.New()
io.WriteString(h, u)
key = string(h.Sum(nil))
}
var buffer bytes.Buffer
buffer.WriteString(prefix)
buffer.WriteString(":")
buffer.WriteString(key)
return buffer.String()
}
func newCachedWriter(store persistence.CacheStore, expire time.Duration, writer gin.ResponseWriter, key string) *cachedWriter {
return &cachedWriter{writer, 0, false, store, expire, key}
}
func (w *cachedWriter) WriteHeader(code int) {
w.status = code
w.written = true
w.ResponseWriter.WriteHeader(code)
}
func (w *cachedWriter) Status() int {
return w.ResponseWriter.Status()
}
func (w *cachedWriter) Written() bool {
return w.ResponseWriter.Written()
}
func (w *cachedWriter) Write(data []byte) (int, error) {
ret, err := w.ResponseWriter.Write(data)
if err == nil {
store := w.store
var cache responseCache
if err := store.Get(w.key, &cache); err == nil {
cache.Data = []byte{}
data = append(cache.Data, data...)
}
//cache responses with a status code < 300
if w.Status() < 300 {
val := responseCache{
w.Status(),
w.Header(),
data,
}
err = store.Set(w.key, val, w.expire)
if err != nil {
// need logger
}
}
}
return ret, err
}
func (w *cachedWriter) WriteString(data string) (n int, err error) {
ret, err := w.ResponseWriter.WriteString(data)
//cache responses with a status code < 300
if err == nil && w.Status() < 300 {
store := w.store
val := responseCache{
w.Status(),
w.Header(),
[]byte(data),
}
store.Set(w.key, val, w.expire)
}
return ret, err
}
// Cache Middleware
func Cache(store *persistence.CacheStore) gin.HandlerFunc {
return func(c *gin.Context) {
c.Set(CACHE_MIDDLEWARE_KEY, store)
c.Next()
}
}
func SiteCache(store persistence.CacheStore, expire time.Duration) gin.HandlerFunc {
return func(c *gin.Context) {
var cache responseCache
url := c.Request.URL
key := CreateKey(url.RequestURI())
if err := store.Get(key, &cache); err != nil {
c.Next()
} else {
c.Writer.WriteHeader(cache.Status)
for k, vals := range cache.Header {
for _, v := range vals {
c.Writer.Header().Set(k, v)
}
}
c.Writer.Write(cache.Data)
}
}
}
// CachePage Decorator
func CachePage(store persistence.CacheStore, expire time.Duration, handle gin.HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
var cache responseCache
url := c.Request.URL
key := CreateKey(url.RequestURI())
if err := store.Get(key, &cache); err != nil {
if err != persistence.ErrCacheMiss {
log.Println(err.Error())
}
// replace writer
writer := newCachedWriter(store, expire, c.Writer, key)
c.Writer = writer
handle(c)
// Drop caches of aborted contexts
if c.IsAborted() {
store.Delete(key)
}
} else {
c.Writer.WriteHeader(cache.Status)
for k, vals := range cache.Header {
for _, v := range vals {
c.Writer.Header().Set(k, v)
}
}
c.Writer.Write(cache.Data)
}
}
}
// CachePageWithoutQuery add ability to ignore GET query parameters.
func CachePageWithoutQuery(store persistence.CacheStore, expire time.Duration, handle gin.HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
var cache responseCache
key := CreateKey(c.Request.URL.Path)
if err := store.Get(key, &cache); err != nil {
if err != persistence.ErrCacheMiss {
log.Println(err.Error())
}
// replace writer
writer := newCachedWriter(store, expire, c.Writer, key)
c.Writer = writer
handle(c)
} else {
c.Writer.WriteHeader(cache.Status)
for k, vals := range cache.Header {
for _, v := range vals {
c.Writer.Header().Set(k, v)
}
}
c.Writer.Write(cache.Data)
}
}
}
// CachePageAtomic Decorator
func CachePageAtomic(store persistence.CacheStore, expire time.Duration, handle gin.HandlerFunc) gin.HandlerFunc {
var m sync.Mutex
p := CachePage(store, expire, handle)
return func(c *gin.Context) {
m.Lock()
defer m.Unlock()
p(c)
}
}
func CachePageWithoutHeader(store persistence.CacheStore, expire time.Duration, handle gin.HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
var cache responseCache
url := c.Request.URL
key := CreateKey(url.RequestURI())
if err := store.Get(key, &cache); err != nil {
if err != persistence.ErrCacheMiss {
log.Println(err.Error())
}
// replace writer
writer := newCachedWriter(store, expire, c.Writer, key)
c.Writer = writer
handle(c)
// Drop caches of aborted contexts
if c.IsAborted() {
store.Delete(key)
}
} else {
c.Writer.WriteHeader(cache.Status)
c.Writer.Write(cache.Data)
}
}
}