-
Notifications
You must be signed in to change notification settings - Fork 1
/
proxy_cache.go
49 lines (43 loc) · 1 KB
/
proxy_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
package main
import (
"net/http"
)
type CachingProxy struct {
store interface {
Exists(string) bool
Get(string) ([]byte, map[string][]string, error)
Save(string, []byte, map[string][]string) error
}
proxy http.Handler
}
func (p *CachingProxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {
skipCache, ok := req.Context().Value(ContextCacheSkipKey).(bool)
if ok && skipCache {
w.Header().Add("X-Cache", "miss")
p.proxy.ServeHTTP(w, req)
return
}
cacheReq := CacheableRequest{req}
id, err := cacheReq.GetID()
if err != nil {
http.Error(w, "failed to read request id", http.StatusInternalServerError)
return
}
if p.store.Exists(id) {
w.Header().Add("X-Cache", "hit")
data, _, err := p.store.Get(id)
if err != nil {
http.Error(w, "cache hit failed", http.StatusInternalServerError)
return
}
w.Write(data)
return
}
w.Header().Add("X-Cache", "miss")
w = &CachingResponseWriter{
id: id,
writer: w,
cacheStore: p.store,
}
p.proxy.ServeHTTP(w, req)
}