-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcache_backend.go
92 lines (70 loc) · 1.79 KB
/
cache_backend.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
package templar
import (
"bytes"
"io/ioutil"
"net/http"
"time"
"github.com/vektra/templar/cache"
)
type Cache struct {
c cache.Cache
}
func NewMemoryCache(expire time.Duration) *Cache {
return &Cache{
c: cache.NewInMemoryCache(expire),
}
}
func NewMemcacheCache(hostlist []string, expire time.Duration) *Cache {
return &Cache{
c: cache.NewMemcachedCache(hostlist, expire),
}
}
func NewRedisCache(host string, password string, expire time.Duration) *Cache {
return &Cache{
c: cache.NewRedisCache(host, password, expire),
}
}
func NewGroupCacheCache(thisPeerURL string, otherPeersURLs string, defaultExpiration time.Duration, memoryLimit int64, transport Transport) *cache.GroupCacheCache {
return cache.NewGroupCacheCache(thisPeerURL, otherPeersURLs, defaultExpiration, memoryLimit, transport)
}
type cachedRequest struct {
body []byte
status int
headers http.Header
}
func (m *Cache) Set(req *http.Request, resp *http.Response) {
cr := &cachedRequest{}
if resp.Body != nil {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
cr.body = body
resp.Body = ioutil.NopCloser(bytes.NewReader(body))
}
cr.status = resp.StatusCode
cr.headers = resp.Header
var expires time.Duration
if reqExpire := req.Header.Get(CacheTimeHeader); reqExpire != "" {
if dur, err := time.ParseDuration(reqExpire); err == nil {
expires = dur
}
}
m.c.Add(req.URL.String(), cr, expires)
}
func (m *Cache) Get(req *http.Request) (*http.Response, bool) {
var cr *cachedRequest
err := m.c.Get(req.URL.String(), &cr)
if err != nil {
return nil, false
}
resp := &http.Response{
StatusCode: cr.status,
Header: make(http.Header),
}
for k, v := range cr.headers {
resp.Header[k] = v
}
resp.Body = ioutil.NopCloser(bytes.NewReader(cr.body))
return resp, true
}