-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcache.go
100 lines (73 loc) · 2.16 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
package templar
import "net/http"
type FallbackCacher struct {
backend CacheBackend
transport Transport
categorizer *Categorizer
}
var _ = Transport(&FallbackCacher{})
func NewFallbackCacher(backend CacheBackend, transport Transport, categorizer *Categorizer) *FallbackCacher {
return &FallbackCacher{backend, transport, categorizer}
}
const (
CacheHeader = "X-Templar-Cache"
CacheTimeHeader = "X-Templar-CacheFor"
CacheCachedHeader = "X-Templar-Cached"
)
func (c *FallbackCacher) shouldCache(req *http.Request) bool {
return c.categorizer.Stateless(req) && req.Header.Get(CacheHeader) == "fallback"
}
func (c *FallbackCacher) RoundTrip(req *http.Request) (*http.Response, error) {
upstream, err := c.transport.RoundTrip(req)
if !c.shouldCache(req) {
return upstream, err
}
if err != nil {
return nil, err
}
c.backend.Set(req, upstream)
return upstream, nil
}
func (c *FallbackCacher) Fallback(req *http.Request) (*http.Response, error) {
if upstream, ok := c.backend.Get(req); ok {
if upstream != nil {
upstream.Header.Add(CacheCachedHeader, "yes")
return upstream, nil
}
}
return nil, nil
}
func (c *FallbackCacher) CancelRequest(req *http.Request) {
c.transport.CancelRequest(req)
}
type EagerCacher struct {
backend CacheBackend
transport Transport
categorizer *Categorizer
}
var _ = Transport(&EagerCacher{})
func NewEagerCacher(backend CacheBackend, transport Transport, categorizer *Categorizer) *EagerCacher {
return &EagerCacher{backend, transport, categorizer}
}
func (c *EagerCacher) shouldCache(req *http.Request) bool {
return c.categorizer.Stateless(req) && req.Header.Get(CacheHeader) == "eager"
}
func (c *EagerCacher) RoundTrip(req *http.Request) (*http.Response, error) {
if !c.shouldCache(req) {
upstream, err := c.transport.RoundTrip(req)
return upstream, err
}
if upstream, ok := c.backend.Get(req); ok {
upstream.Header.Add(CacheCachedHeader, "yes")
return upstream, nil
}
upstream, err := c.transport.RoundTrip(req)
if err != nil {
return nil, err
}
c.backend.Set(req, upstream)
return upstream, nil
}
func (c *EagerCacher) CancelRequest(req *http.Request) {
c.transport.CancelRequest(req)
}