-
Notifications
You must be signed in to change notification settings - Fork 199
/
util.go
82 lines (72 loc) · 2.01 KB
/
util.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
package http
import (
"net/http"
"time"
)
// CacheControlPublicHandler is a net/http.Handler implementation that sets the "Cache-Control" header to "public".
//
// It only sets the header if the status code is StatusOK/204 or StatusNotModified/304.
type CacheControlPublicHandler struct {
http.Handler
}
// ServeHTTP implements net/http.Handler
func (h *CacheControlPublicHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
hrw := &headerResponseWriter{
ResponseWriter: rw,
OnWriteHeaderFunc: func(code int) {
if code == http.StatusOK || code == http.StatusNotModified {
rw.Header().Set("Cache-Control", "public")
}
},
}
h.Handler.ServeHTTP(hrw, req)
}
var expiresHeaderLocation = getTimeLocation("GMT")
func getTimeLocation(name string) *time.Location {
l, err := time.LoadLocation(name)
if err != nil {
panic(err)
}
return l
}
// ExpiresHandler is a net/http.Handler implementation that sets the "Expires" header.
//
// It only sets the header if the status code is StatusOK/204 or StatusNotModified/304.
type ExpiresHandler struct {
http.Handler
Expires time.Duration
}
// ServeHTTP implements net/http.Handler.
func (eh *ExpiresHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
hrw := &headerResponseWriter{
ResponseWriter: rw,
OnWriteHeaderFunc: func(code int) {
if code == http.StatusOK || code == http.StatusNotModified {
t := time.Now()
t = t.Add(eh.Expires)
t = t.In(expiresHeaderLocation)
rw.Header().Set("Expires", t.Format(time.RFC1123))
}
},
}
eh.Handler.ServeHTTP(hrw, req)
}
type headerResponseWriter struct {
http.ResponseWriter
OnWriteHeaderFunc func(code int)
wroteHeader bool
}
func (hrw *headerResponseWriter) Write(data []byte) (int, error) {
if !hrw.wroteHeader {
hrw.WriteHeader(http.StatusOK)
}
return hrw.ResponseWriter.Write(data)
}
func (hrw *headerResponseWriter) WriteHeader(code int) {
if hrw.wroteHeader {
return
}
hrw.OnWriteHeaderFunc(code)
hrw.ResponseWriter.WriteHeader(code)
hrw.wroteHeader = true
}