-
Notifications
You must be signed in to change notification settings - Fork 3
/
cache.go
197 lines (165 loc) · 3.43 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 cache
import (
"bytes"
"crypto/md5"
"encoding/gob"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
)
const KEY_PREFIX = "gin:cache:"
var (
ErrNotFound = errors.New("not found")
ErrAlreadyExists = errors.New("already exists")
)
type Cached struct {
Status int
Body []byte
Header http.Header
ExpireAt time.Duration
}
type Store interface {
Get(string) ([]byte, error)
Set(string, string, time.Duration) error
Remove(string) error
Update(string, string, time.Duration) error
}
type Options struct {
Store Store
Expire time.Duration
Headers []string
DoNotUseAbort bool
}
func (o *Options) init() {
if o.Headers == nil {
o.Headers = []string{
"User-Agent",
"Accept",
"Accept-Encoding",
"Accept-Language",
"Cookie",
"User-Agent",
}
}
}
type Cache struct {
Store
options Options
expires map[string]time.Time
}
func (c *Cache) Get(key string) (*Cached, error) {
if data, err := c.Store.Get(key); err == nil {
var cch *Cached
dec := gob.NewDecoder(bytes.NewBuffer(data))
dec.Decode(&cch)
return cch, nil
} else {
return nil, err
}
}
func (c *Cache) Set(key string, cch *Cached) error {
var b bytes.Buffer
enc := gob.NewEncoder(&b)
panicIf(enc.Encode(*cch))
return c.Store.Set(key, string(b.Bytes()), cch.ExpireAt)
}
func (c *Cache) Update(key string, cch *Cached) error {
var b bytes.Buffer
enc := gob.NewEncoder(&b)
panicIf(enc.Encode(*cch))
return c.Store.Update(key, string(b.Bytes()), cch.ExpireAt)
}
type wrappedWriter struct {
gin.ResponseWriter
body bytes.Buffer
}
func (rw *wrappedWriter) Write(body []byte) (int, error) {
n, err := rw.ResponseWriter.Write(body)
if err == nil {
rw.body.Write(body)
}
return n, err
}
func New(o ...Options) gin.HandlerFunc {
opts := Options{
Store: NewRedis(nil),
Expire: 0,
}
for _, i := range o {
opts = i
break
}
opts.init()
cache := Cache{
Store: opts.Store,
options: opts,
expires: make(map[string]time.Time),
}
return func(c *gin.Context) {
// only GET method available for caching
if c.Request.Method != "GET" {
c.Next()
return
}
tohash := c.Request.URL.RequestURI()
for _, k := range cache.options.Headers {
if v, ok := c.Request.Header[k]; ok {
tohash += k
tohash += strings.Join(v, "")
}
}
key := KEY_PREFIX + md5String(tohash)
if cch, _ := cache.Get(key); cch == nil {
// cache miss
writer := c.Writer
rw := wrappedWriter{ResponseWriter: c.Writer}
c.Writer = &rw
c.Next()
c.Writer = writer
cache.Set(key, &Cached{
Status: rw.Status(),
Body: rw.body.Bytes(),
Header: http.Header(rw.Header()),
ExpireAt: func() time.Duration {
if cache.options.Expire == 0 {
return (5 * time.Minute)
} else {
return cache.options.Expire
}
}(),
})
} else {
// cache found
start := time.Now()
c.Writer.WriteHeader(cch.Status)
for k, val := range cch.Header {
for _, v := range val {
c.Writer.Header().Add(k, v)
}
}
c.Writer.Header().Add("X-Gin-Cache", fmt.Sprintf("%f ms", time.Now().Sub(start).Seconds()*1000))
c.Writer.Write(cch.Body)
if !cache.options.DoNotUseAbort {
c.Abort()
}
}
}
}
func md5String(url string) string {
h := md5.New()
io.WriteString(h, url)
return hex.EncodeToString(h.Sum(nil))
}
func init() {
gob.Register(Cached{})
}
func panicIf(err error) {
if err != nil {
panic(err)
}
}