-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
195 lines (167 loc) · 3.47 KB
/
cache.go
File metadata and controls
195 lines (167 loc) · 3.47 KB
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
package cache
import (
"bytes"
"crypto/md5"
"encoding/gob"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
)
const keyPrefix = "cache:"
var (
errNotFound = errors.New("not found")
errAlreadyExists = errors.New("already exists")
)
// Cached is a cached item
type Cached struct {
Status int
Body []byte
Header http.Header
ExpireAt time.Time
}
// Store interface for filesystems to implement
type Store interface {
Get(string) ([]byte, error)
Set(string, []byte) error
Remove(string) error
}
// Options for cache
type Options struct {
Store Store
Expire time.Duration
Headers []string
StripHeaders []string
BypassCodes map[int]bool
DoNotUseAbort bool
}
// Cache struct implements Store interface
type Cache struct {
Store
options Options
expires map[string]time.Time
}
// Get cache value
func (c *Cache) Get(key string) (*Cached, error) {
data, err := c.Store.Get(key)
if err != nil {
return nil, err
}
var cch *Cached
dec := gob.NewDecoder(bytes.NewBuffer(data))
err = dec.Decode(&cch)
if err != nil {
return nil, err
}
if cch.ExpireAt.Nanosecond() != 0 && cch.ExpireAt.Before(time.Now()) {
err := c.Store.Remove(key)
return nil, err
}
return cch, nil
}
// Set cache value
func (c *Cache) Set(key string, cch *Cached) error {
var b bytes.Buffer
enc := gob.NewEncoder(&b)
err := enc.Encode(*cch)
if err != nil {
return err
}
return c.Store.Set(key, b.Bytes())
}
type wrappedWriter struct {
gin.ResponseWriter
body bytes.Buffer
}
// Write response
func (rw *wrappedWriter) Write(body []byte) (int, error) {
n, err := rw.ResponseWriter.Write(body)
if err == nil {
rw.body.Write(body)
}
return n, err
}
// New cache
func New(o ...Options) gin.HandlerFunc {
opts := Options{
Store: NewInMemory(),
Expire: 0,
}
for _, i := range o {
opts = i
break
}
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 := keyPrefix + 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
header := rw.Header()
for _, k := range cache.options.StripHeaders {
header.Del(k)
}
if cache.options.BypassCodes[rw.Status()] {
c.Next()
return
}
cache.Set(key, &Cached{
Status: rw.Status(),
Body: rw.body.Bytes(),
Header: rw.Header(),
ExpireAt: func() time.Time {
if cache.options.Expire == 0 {
return time.Time{}
}
return time.Now().Add(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.Since(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{})
}