This repository has been archived by the owner on May 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
pragma.go
85 lines (77 loc) · 2.15 KB
/
pragma.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
package cachekit
import (
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
const (
// HeaderCacheControl as in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
HeaderCacheControl = "Cache-Control"
// HeaderExpires as in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expires
HeaderExpires = "Expires"
// HeaderLastModified as in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
HeaderLastModified = "Last-Modified"
// HeaderIfModifiedSince as in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since
HeaderIfModifiedSince = "If-Modified-Since"
)
type (
// Pragma handle pragmatic information/directives for caching
Pragma struct {
IfModifiedSince time.Time
LastModified time.Time
NoCache bool
MaxAge time.Duration
Expires time.Time
}
)
// CreatePragma to create new instance of CacheControl from request
func CreatePragma(header http.Header) *Pragma {
var noCache bool
var ifModifiedSince time.Time
var maxAge time.Duration
ifModifiedSince = ParseTime(header.Get(HeaderIfModifiedSince))
if raw := header.Get(HeaderCacheControl); raw != "" {
for _, s := range strings.Split(raw, ",") {
s = strings.ToLower(strings.TrimSpace(s))
if s == "no-cache" {
noCache = true
}
maxAgeField := "max-age="
if strings.HasPrefix(s, maxAgeField) {
maxAgeRaw, err := strconv.Atoi(s[len(maxAgeField):])
if err != nil {
break
}
maxAge = time.Duration(maxAgeRaw) * time.Second
}
}
}
return &Pragma{
IfModifiedSince: ifModifiedSince,
NoCache: noCache,
MaxAge: maxAge,
}
}
// Header set header
func (c *Pragma) Header() http.Header {
header := make(http.Header)
if !c.Expires.IsZero() {
header.Add(HeaderExpires, FormatTime(c.Expires))
}
if !c.LastModified.IsZero() {
header.Add(HeaderLastModified, FormatTime(c.LastModified))
}
header.Add(HeaderCacheControl, c.String())
return header
}
func (c *Pragma) String() string {
var cc []string
if c.NoCache {
cc = append(cc, "no-cache")
} else {
cc = append(cc, fmt.Sprintf("max-age=%d", int(c.MaxAge.Seconds())))
}
return strings.Join(cc, " ")
}