-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
158 lines (126 loc) · 3.51 KB
/
handler.go
File metadata and controls
158 lines (126 loc) · 3.51 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"net/http"
"net/http/httputil"
"strings"
"time"
"github.com/google/uuid"
"github.com/go-http-utils/fresh"
uh "github.com/go-http-utils/headers"
)
type CacheHandler struct {
client *http.Client
logger Logger
}
func NewCacheHandler(client *http.Client, logger Logger) *CacheHandler {
return &CacheHandler{client, logger}
}
func (h *CacheHandler) Handle(cnf *ClientConfig) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet {
h.logger.Error(fmt.Sprintf("response caching is not supported for %s %s", req.Method, req.URL.RequestURI()))
h.writeResponse(w, &http.Response{StatusCode: http.StatusNotImplemented})
return
}
reqClone := cloneRequest(req)
res := h.loadFromCache(reqClone, cnf)
if res == nil {
res = h.makeRequest(reqClone)
if isResponseCacheable(res) {
h.saveToCache(res, cnf)
}
}
if fresh.IsFresh(req.Header, res.Header) {
res.StatusCode = http.StatusNotModified
res.Body = nil
}
h.writeResponse(w, res)
})
}
func (h *CacheHandler) makeRequest(req *http.Request) *http.Response {
res, err := h.client.Do(req)
if err != nil {
h.logger.Error(err)
return &http.Response{StatusCode: http.StatusInternalServerError}
}
res.Body = io.NopCloser(ReusableReader(res.Body))
return res
}
func (h *CacheHandler) loadFromCache(req *http.Request, cnf *ClientConfig) *http.Response {
conn := GetCache(cnf.Conn)
if conn == nil {
h.logger.Error(fmt.Sprintf("conn %s not found", cnf.Conn))
return nil
}
v, err := conn.Fetch(cacheKey(req, cnf))
if err != nil {
return nil
}
buf := bufio.NewReader(bytes.NewReader([]byte(v)))
r, err := http.ReadResponse(buf, nil)
if err != nil {
h.logger.Error("can't read from cache")
return nil
}
return r
}
func (h *CacheHandler) saveToCache(res *http.Response, cnf *ClientConfig) {
dump, err := httputil.DumpResponse(res, true)
if err != nil {
h.logger.Error("can't dump response")
return
}
conn := GetCache(cnf.Conn)
if conn == nil {
h.logger.Error(fmt.Sprintf("conn %s not found", cnf.Conn))
return
}
err = conn.Save(cacheKey(res.Request, cnf), string(dump), time.Duration(cnf.Ttl)*time.Second)
if err != nil {
h.logger.Error(fmt.Sprintf("failed save to cache: %v", err))
}
}
func (h *CacheHandler) writeResponse(w http.ResponseWriter, res *http.Response) {
for k, hs := range res.Header {
for _, h := range hs {
w.Header().Add(k, h)
}
}
w.WriteHeader(res.StatusCode)
if res.Body == nil {
return
}
_, err := io.Copy(w, res.Body)
if err != nil {
h.logger.Error(fmt.Sprintf("failed write response body: %v", err))
}
_ = res.Body.Close()
}
func isResponseCacheable(r *http.Response) bool {
return r.StatusCode >= 200 && r.StatusCode <= 299
}
func cloneRequest(req *http.Request) *http.Request {
clone := req.Clone(req.Context())
clone.Header.Del(uh.IfModifiedSince)
clone.Header.Del(uh.IfUnmodifiedSince)
clone.Header.Del(uh.IfNoneMatch)
clone.Header.Del(uh.IfMatch)
clone.Header.Del(uh.CacheControl)
clone.Header.Del(uh.AcceptEncoding)
return clone
}
func cacheKey(req *http.Request, cnf *ClientConfig) string {
url := req.URL.RequestURI()
var headers []string
for _, h := range cnf.Headers {
if val := req.Header.Values(h); val != nil {
headers = append(headers, fmt.Sprintf("%s:%s", strings.ToLower(h), strings.Join(val, ",")))
}
}
url += "|headers:" + strings.Join(headers, "/")
return fmt.Sprintf("krakend-hc:%s", uuid.NewSHA1(uuid.NameSpaceURL, []byte(url)))
}