-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
251 lines (227 loc) · 5.69 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
package gin_api_cache
import (
"bytes"
"context"
"fmt"
"log"
"net/http"
"sort"
"time"
"github.com/gin-gonic/gin"
"github.com/janartist/gin-api-cache/store"
)
const (
DefaultExpire = time.Minute
ForeverExpire = time.Duration(-1)
CachePrefix = "url_data_cache:"
ResponseCacheContextKey = "responseCache"
)
const (
SuccessEnableMode Mode = iota + 1
ALLEnableMode
CustomEnableMode
)
const (
CacheSource Source = iota + 1
LocalSource
)
var (
responseCacheNotFoundError = fmt.Errorf("responseCache notFound")
)
func New(c CacheStore, ac bool, mode Mode, fn func(*store.ResponseCache) bool) *CacheManager {
return &CacheManager{c, &Group{}, ac, mode, fn}
}
func NewDefault(conf *store.RedisConf) *CacheManager {
cache := New(store.NewRedisStoreDefault(conf), true, SuccessEnableMode, nil)
return cache
}
func Key(key string) CeOpt {
return func(c *Cache) { c.Key = key }
}
func KMap(kMap map[string]string) CeOpt {
return func(c *Cache) {
c.KMap = kMap
}
}
func Ttl(ttl time.Duration) CeOpt {
return func(c *Cache) { c.Ttl = ttl }
}
func Single(s bool) CeOpt {
return func(c *Cache) { c.Single = s }
}
func Remove(ctx context.Context, m *CacheManager, key string) error {
err := m.Store.Remove(ctx, CachePrefix+key)
return err
}
// CacheFunc Cache Decorator
func CacheFunc(m *CacheManager, opts ...CeOpt) gin.HandlerFunc {
ce := &Cache{Single: true}
for _, opt := range opts {
opt(ce)
}
if ce.Ttl == 0 {
ce.Ttl = DefaultExpire
}
return func(ctx *gin.Context) {
ce2 := *ce
if ce2.Key == "" {
ce2.Key = ctx.Request.URL.Path
}
if ce2.KMap != nil {
ce2.Key = ce2.Key + makeMapSortToString(ce2.KMap)
}
cc := &CacheContext{ctx, m, ce2, ctx.Request.RequestURI}
cache := store.ResponseCache{Header: make(map[string][]string)}
//from cache
if err := m.Store.Get(ctx, CachePrefix+cc.Cache.Key, cc.requestPath, &cache); err == nil {
if m.AddCacheHeader {
cache.AddCacheHeader(cc.requestPath, int8(CacheSource))
}
cache.Write(ctx.Writer)
ctx.Abort()
return
}
doFunc := func(c *gin.Context) (interface{}, error) {
w := c.Writer
// replace writer, add set context ResponseCacheContextKey
c.Writer = newCacheWriter(c.Writer, cc)
//此处Next()应执行业务逻辑,执行完后response应写入完毕,或c.Writer被篡改
c.Next()
//get context ResponseCacheContextKey read response
cFromContext, ok := c.Get(ResponseCacheContextKey)
if !ok {
return nil, responseCacheNotFoundError
}
c.Writer = w
responseCache := cFromContext.(*store.ResponseCache)
if m.IsOK(responseCache) {
if err := m.Store.Set(c, CachePrefix+cc.Cache.Key, cc.requestPath, responseCache, ce2.Ttl); err != nil {
log.Printf("cache store set err:%v", err)
}
}
if m.AddCacheHeader {
responseCache.AddCacheHeader(cc.requestPath, int8(LocalSource))
}
return responseCache, nil
}
if !ce2.Single {
// replace writer
doFunc(ctx)
return
}
isWrite := false
val, err := m.group.Do(cc.requestPath, func() (interface{}, error) {
isWrite = true
//TODO add MutexLock
return doFunc(ctx)
})
// from localCache
if !isWrite && err == nil {
v := val.(*store.ResponseCache)
v.Write(ctx.Writer)
}
if err != nil {
log.Printf("local cache get err:%v", err)
}
ctx.Abort()
return
}
}
type Mode int8
type Source int8
type CacheManager struct {
Store CacheStore
group *Group
AddCacheHeader bool
Mode Mode
CustomEnableModeFunc func(*store.ResponseCache) bool
}
// IsOK 是否OK需要缓存
func (m *CacheManager) IsOK(c *store.ResponseCache) bool {
if m.Mode == ALLEnableMode {
return true
}
if m.Mode == SuccessEnableMode {
return c.Status < http.StatusMultipleChoices && c.Status >= http.StatusOK
}
if m.Mode == CustomEnableMode && m.CustomEnableModeFunc != nil {
return m.CustomEnableModeFunc(c)
}
return false
}
type CacheStore interface {
Get(context.Context, string, string, *store.ResponseCache) error
Set(context.Context, string, string, *store.ResponseCache, time.Duration) error
Remove(context.Context, string) error
}
// CeOpt is an application option.
type CeOpt func(*Cache)
type Cache struct {
Key string
KMap map[string]string
Ttl time.Duration
Single bool
}
type CacheContext struct {
*gin.Context
*CacheManager
Cache
requestPath string
}
func (c *CacheContext) Remove() error {
return Remove(c.Context, c.CacheManager, c.Key)
}
type cacheWriter struct {
gin.ResponseWriter
cc *CacheContext
}
//重写底层write方法,获取response存入上下文,其余不更改
func (w *cacheWriter) Write(data []byte) (int, error) {
ret, err := w.ResponseWriter.Write(data)
if err == nil {
//cache response
val := &store.ResponseCache{
Status: w.Status(),
Header: w.Header(),
Data: data,
}
w.cc.Context.Set(ResponseCacheContextKey, val)
}
return ret, err
}
func newCacheWriter(writer gin.ResponseWriter, cc *CacheContext) *cacheWriter {
return &cacheWriter{writer, cc}
}
//func urlEscape(prefix string, u string) string {
// key := url.QueryEscape(u)
// if len(key) > 200 {
// h := sha1.New()
// _, err := io.WriteString(h, u)
// if err != nil {
// return ""
// }
// key = string(h.Sum(nil))
// }
// var buffer bytes.Buffer
// buffer.WriteString(prefix)
// buffer.WriteString(":")
// buffer.WriteString(key)
// return buffer.String()
//}
//map至有序字符串
func makeMapSortToString(m map[string]string) string {
var keys []string
for k := range m {
keys = append(keys, k)
}
sort.Sort(sort.StringSlice(keys))
var buffer bytes.Buffer
for _, k := range keys {
v, _ := m[k]
buffer.WriteString("&")
buffer.WriteString(k)
buffer.WriteString("=")
buffer.WriteString(v)
}
return buffer.String()
}