This repository has been archived by the owner on Apr 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathcachecontrol.go
109 lines (95 loc) · 2.01 KB
/
cachecontrol.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
package httpcache
import (
"bytes"
"fmt"
"net/http"
"sort"
"strings"
"time"
)
const (
CacheControlHeader = "Cache-Control"
)
type CacheControl map[string][]string
func ParseCacheControlHeaders(h http.Header) (CacheControl, error) {
return ParseCacheControl(strings.Join(h["Cache-Control"], ", "))
}
func ParseCacheControl(input string) (CacheControl, error) {
cc := make(CacheControl)
length := len(input)
isValue := false
lastKey := ""
for pos := 0; pos < length; pos++ {
var token string
switch input[pos] {
case '"':
if offset := strings.IndexAny(input[pos+1:], `"`); offset != -1 {
token = input[pos+1 : pos+1+offset]
} else {
token = input[pos+1:]
}
pos += len(token) + 1
case ',', '\n', '\r', ' ', '\t':
continue
case '=':
isValue = true
continue
default:
if offset := strings.IndexAny(input[pos:], "\"\n\t\r ,="); offset != -1 {
token = input[pos : pos+offset]
} else {
token = input[pos:]
}
pos += len(token) - 1
}
if isValue {
cc.Add(lastKey, token)
isValue = false
} else {
cc.Add(token, "")
lastKey = token
}
}
return cc, nil
}
func (cc CacheControl) Get(key string) (string, bool) {
v, exists := cc[key]
if exists && len(v) > 0 {
return v[0], true
}
return "", exists
}
func (cc CacheControl) Add(key, val string) {
if !cc.Has(key) {
cc[key] = []string{}
}
if val != "" {
cc[key] = append(cc[key], val)
}
}
func (cc CacheControl) Has(key string) bool {
_, exists := cc[key]
return exists
}
func (cc CacheControl) Duration(key string) (time.Duration, error) {
d, _ := cc.Get(key)
return time.ParseDuration(d + "s")
}
func (cc CacheControl) String() string {
keys := make([]string, len(cc))
for k, _ := range cc {
keys = append(keys, k)
}
sort.Strings(keys)
buf := bytes.Buffer{}
for _, k := range keys {
vals := cc[k]
if len(vals) == 0 {
buf.WriteString(k + ", ")
}
for _, val := range vals {
buf.WriteString(fmt.Sprintf("%s=%q, ", k, val))
}
}
return strings.TrimSuffix(buf.String(), ", ")
}