-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
84 lines (71 loc) · 1.67 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
package urlcache
import (
"bytes"
"crypto/md5"
"encoding/hex"
"net/http"
"strings"
"sync"
"github.com/marcw/cachecontrol"
)
// 2017/10/20 inada-s Expireを設定したほうがリクエスト数が減ってスコアが下がる現象がみられたため、Expiresは見ないことにした。
type CacheStore struct {
sync.Mutex
items map[string]*URLCache
}
func NewCacheStore() *CacheStore {
return &CacheStore{
items: make(map[string]*URLCache),
}
}
func (c *CacheStore) Get(key string) (*URLCache, bool) {
c.Lock()
v, found := c.items[key]
c.Unlock()
return v, found
}
func (c *CacheStore) Set(key string, value *URLCache) {
c.Lock()
if value == nil {
delete(c.items, key)
} else {
c.items[key] = value
}
c.Unlock()
}
func (c *CacheStore) Del(key string) {
c.Lock()
delete(c.items, key)
c.Unlock()
}
type URLCache struct {
LastModified string
Etag string
CacheControl *cachecontrol.CacheControl
MD5 string
}
func NewURLCache(res *http.Response, body *bytes.Buffer) (*URLCache, string) {
md5Sum := md5.Sum(body.Bytes())
hash := hex.EncodeToString(md5Sum[:])
ccs := res.Header["Cache-Control"]
directive := strings.Join(ccs, " ")
cc := cachecontrol.Parse(directive)
noCache, _ := cc.NoCache()
if len(directive) == 0 || noCache || cc.NoStore() {
return nil, hash
}
return &URLCache{
LastModified: res.Header.Get("Last-Modified"),
Etag: res.Header.Get("ETag"),
CacheControl: &cc,
MD5: hash,
}, hash
}
func (c *URLCache) ApplyRequest(req *http.Request) {
if c.LastModified != "" {
req.Header.Add("If-Modified-Since", c.LastModified)
}
if c.Etag != "" {
req.Header.Add("If-None-Match", c.Etag)
}
}