-
Notifications
You must be signed in to change notification settings - Fork 26
/
cache.go
197 lines (167 loc) · 4.75 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 main
import (
"context"
"net/http"
"net/url"
"sort"
"time"
"github.com/samber/go-singleflightx"
"go.goblog.app/app/pkgs/bodylimit"
"go.goblog.app/app/pkgs/bufferpool"
c "go.goblog.app/app/pkgs/cache"
)
const (
cacheLoggedInKey contextKey = "cacheLoggedIn"
cacheExpirationKey contextKey = "cacheExpiration"
cacheControl = "Cache-Control"
)
type cache struct {
g singleflightx.Group[string, *cacheItem]
c *c.Cache[string, *cacheItem]
}
func (a *goBlog) initCache() error {
if a.cfg.Cache != nil && !a.cfg.Cache.Enable {
return nil // Cache disabled
}
a.cache = &cache{
c: c.New[string, *cacheItem](time.Minute, 20*bodylimit.MB),
}
return nil
}
func cacheLoggedIn(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), cacheLoggedInKey, true)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (a *goBlog) cacheMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if a.cache == nil || a.cache.c == nil || !isCacheable(r) || a.shouldSkipLoggedIn(r) {
next.ServeHTTP(w, r)
return
}
key := generateCacheKey(r)
ci, _, _ := a.cache.g.Do(key, func() (*cacheItem, error) {
return a.cache.getOrCreateCache(key, next, r), nil
})
a.serveCachedResponse(w, r, ci)
})
}
func isCacheable(r *http.Request) bool {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
return false
}
return r.URL.Query().Get("cache") != "0" && r.URL.Query().Get("cache") != "false"
}
func (a *goBlog) shouldSkipLoggedIn(r *http.Request) bool {
if cli, ok := r.Context().Value(cacheLoggedInKey).(bool); ok && cli {
setLoggedIn(r, false)
return false
}
return a.isLoggedIn(r)
}
func generateCacheKey(r *http.Request) string {
buf := bufferpool.Get()
defer bufferpool.Put(buf)
// Special cases
if asRequest, ok := r.Context().Value(asRequestKey).(bool); ok && asRequest {
buf.WriteString("as-")
}
if torUsed, ok := r.Context().Value(torUsedKey).(bool); ok && torUsed {
buf.WriteString("tor-")
}
// Add cache URL
buf.WriteString(r.URL.EscapedPath())
if query := r.URL.Query(); len(query) > 0 {
buf.WriteByte('?')
keys := make([]string, 0, len(query))
for k := range query {
keys = append(keys, k)
}
sort.Strings(keys)
for i, k := range keys {
keyEscaped := url.QueryEscape(k)
for j, val := range query[k] {
if i > 0 || j > 0 {
buf.WriteByte('&')
}
buf.WriteString(keyEscaped)
buf.WriteByte('=')
buf.WriteString(url.QueryEscape(val))
}
}
}
return buf.String()
}
func (a *goBlog) serveCachedResponse(w http.ResponseWriter, r *http.Request, ci *cacheItem) {
a.setCacheHeaders(w, ci)
if ifNoneMatchHeader := r.Header.Get("If-None-Match"); ifNoneMatchHeader != "" && ifNoneMatchHeader == ci.eTag {
w.WriteHeader(http.StatusNotModified)
return
}
w.WriteHeader(ci.code)
_, _ = w.Write(ci.body)
}
func (a *goBlog) setCacheHeaders(w http.ResponseWriter, cache *cacheItem) {
// Copy headers
for k, v := range cache.header.Clone() {
w.Header()[k] = v
}
// Set cache headers
w.Header().Set("ETag", cache.eTag)
w.Header().Set(cacheControl, "public,no-cache")
}
func (c *cache) getOrCreateCache(key string, next http.Handler, r *http.Request) *cacheItem {
if rItem, ok := c.c.Get(key); ok {
return rItem
}
// Remove original timeout, add new one
withoutCancelCtx := context.WithoutCancel(r.Context())
newCancelCtx, cancel := context.WithTimeout(withoutCancelCtx, 5*time.Minute)
defer cancel()
cr := r.Clone(newCancelCtx)
removeConditionalHeaders(cr)
rec := newCacheRecorder()
next.ServeHTTP(rec, cr)
item := rec.finish()
item.expiration, _ = cr.Context().Value(cacheExpirationKey).(int)
removeProblematicHeaders(item.header)
if shouldCacheItem(item.header.Get(cacheControl)) {
c.saveCache(key, item)
}
return item
}
func removeConditionalHeaders(r *http.Request) {
headers := []string{"If-Modified-Since", "If-Unmodified-Since", "If-None-Match", "If-Match", "If-Range", "Range"}
for _, h := range headers {
r.Header.Del(h)
}
}
func removeProblematicHeaders(header http.Header) {
headers := []string{"Accept-Ranges", "ETag", "Last-Modified"}
for _, h := range headers {
header.Del(h)
}
}
func shouldCacheItem(cacheControlHeader string) bool {
return !containsStrings(cacheControlHeader, "no-store", "private", "no-cache")
}
func (c *cache) saveCache(key string, item *cacheItem) {
ttl := 6 * time.Hour
if item.expiration > 0 {
ttl = time.Duration(item.expiration) * time.Second
}
c.c.Set(key, item, ttl, item.cost())
}
func (c *cache) purge() {
if c == nil || c.c == nil {
return
}
c.c.Clear()
}
func (a *goBlog) defaultCacheExpiration() int {
if a.cfg.Cache != nil {
return a.cfg.Cache.Expiration
}
return 0
}