-
Notifications
You must be signed in to change notification settings - Fork 0
/
httputils.go
90 lines (74 loc) · 1.82 KB
/
httputils.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
package main
import (
"bufio"
"errors"
"github.com/rs/zerolog/log"
"net"
"net/http"
)
type statusIntercepter struct {
next http.ResponseWriter
statuscode *int
}
func (h statusIntercepter) Header() http.Header {
return h.next.Header()
}
func (h statusIntercepter) Write(data []byte) (int, error) {
return h.next.Write(data)
}
func (h statusIntercepter) WriteHeader(statusCode int) {
h.next.WriteHeader(statusCode)
if h.statuscode != nil {
*h.statuscode = statusCode
}
}
func (h statusIntercepter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
next, ok := h.next.(http.Hijacker)
if !ok {
return nil, nil, errors.New("hijack not supported")
}
return next.Hijack()
}
func createStatusIntercepter(next http.ResponseWriter, i *int) statusIntercepter {
return statusIntercepter{
next: next,
statuscode: i,
}
}
type LoggingHandler struct {
next http.Handler
}
func (h LoggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
statusCode := 200
intercepter := createStatusIntercepter(w, &statusCode)
h.next.ServeHTTP(intercepter, r)
log.Debug().Str("Remote", r.RemoteAddr).
Str("Method", r.Method).
Str("UserAgent", r.UserAgent()).
Str("Path", r.URL.Path).
Int("StatusCode", statusCode).
Msg("Serving page")
}
const (
CachePolicyNever = iota
CachePolicyAlways = iota
)
type CacheHeaderInserter struct {
next http.Handler
policy int
}
func (h CacheHeaderInserter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch h.policy {
case CachePolicyAlways:
w.Header().Set("Cache-Control", "public, max-age=15552000")
case CachePolicyNever:
w.Header().Set("Cache-Control", "no-cache, max-age=0")
}
h.next.ServeHTTP(w, r)
}
func CreateCacheHeaderInserter(next http.Handler, policy int) CacheHeaderInserter {
return CacheHeaderInserter{
next: next,
policy: policy,
}
}