forked from allegro/akubra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
roundtripper_decorators.go
173 lines (145 loc) · 4.32 KB
/
roundtripper_decorators.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
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package httphandler
import (
"encoding/json"
"net/http"
"strings"
"time"
"io/ioutil"
"github.com/allegro/akubra/httphandler/config"
"github.com/allegro/akubra/log"
)
// Decorator is http.RoundTripper interface wrapper
type Decorator func(http.RoundTripper) http.RoundTripper
type loggingRoundTripper struct {
roundTripper http.RoundTripper
accessLog log.Logger
}
func (lrt *loggingRoundTripper) RoundTrip(req *http.Request) (resp *http.Response, err error) {
timeStart := time.Now()
resp, err = lrt.roundTripper.RoundTrip(req)
duration := time.Since(timeStart).Seconds() * 1000
statusCode := http.StatusServiceUnavailable
if resp != nil {
statusCode = resp.StatusCode
}
errStr := ""
if err != nil {
errStr = err.Error()
}
accessLogMessage := NewAccessLogMessage(*req,
statusCode,
duration,
errStr)
jsonb, almerr := json.Marshal(accessLogMessage)
if almerr != nil {
log.Printf("Cannot marshal access log message %s", almerr.Error())
return
}
lrt.accessLog.Printf("%s", jsonb)
return
}
// AccessLogging creares Decorator with access log collector
func AccessLogging(logger log.Logger) Decorator {
return func(rt http.RoundTripper) http.RoundTripper {
return &loggingRoundTripper{roundTripper: rt, accessLog: logger}
}
}
type headersSuplier struct {
requestHeaders config.AdditionalHeaders
responseHeaders config.AdditionalHeaders
roundTripper http.RoundTripper
}
func (hs *headersSuplier) RoundTrip(req *http.Request) (resp *http.Response, err error) {
req.URL.Scheme = "http"
for k, v := range hs.requestHeaders {
_, ok := req.Header[k]
if !ok {
req.Header.Set(k, v)
}
}
// While tcp host is rewritten we need to keep Host header
// intact for sake of s3 authorization
if strings.Contains(req.Host, ".s3.") {
prefix := strings.Split(req.Host, ".s3.")[0]
newhost := prefix + "." + req.URL.Host
req.Header.Set("Host", newhost)
req.Host = newhost
}
resp, err = hs.roundTripper.RoundTrip(req)
if err != nil || resp == nil {
return
}
if resp.Header == nil {
resp.Header = http.Header{}
}
for k, v := range hs.responseHeaders {
_, ok := resp.Header[k]
if !ok {
resp.Header.Set(k, v)
}
}
return
}
// HeadersSuplier creates Decorator which adds headers to request and response
func HeadersSuplier(requestHeaders, responseHeaders config.AdditionalHeaders) Decorator {
return func(roundTripper http.RoundTripper) http.RoundTripper {
return &headersSuplier{
requestHeaders: requestHeaders,
responseHeaders: responseHeaders,
roundTripper: roundTripper}
}
}
type optionsHandler struct {
roundTripper http.RoundTripper
}
func (os optionsHandler) RoundTrip(req *http.Request) (resp *http.Response, err error) {
isOptions := false
if req.Method == "OPTIONS" {
req.Method = "HEAD"
isOptions = true
}
resp, err = os.roundTripper.RoundTrip(req)
if resp != nil && isOptions {
resp.Header.Set("Content-Length", "0")
}
return
}
// OptionsHandler changes OPTIONS method it to HEAD and pass it to
// decorated http.RoundTripper, also clears response content-length header
func OptionsHandler(roundTripper http.RoundTripper) http.RoundTripper {
return optionsHandler{roundTripper: roundTripper}
}
type statusHandler struct {
healthCheckEndpoint string
roundTripper http.RoundTripper
}
func (sh statusHandler) RoundTrip(req *http.Request) (resp *http.Response, err error) {
if strings.ToLower(req.URL.Path) == sh.healthCheckEndpoint {
resp := &http.Response{}
bodyContent := "OK"
resp.Body = ioutil.NopCloser(strings.NewReader(bodyContent))
resp.ContentLength = int64(len(bodyContent))
resp.Header = make(http.Header)
resp.Header.Set("Cache-Control", "no-cache, no-store")
resp.Header.Set("Content-Type", "text/plain")
resp.StatusCode = http.StatusOK
return resp, nil
}
return sh.roundTripper.RoundTrip(req)
}
// HealthCheckHandler serving health check endpoint
func HealthCheckHandler(healthCheckEndpoint string) Decorator {
return func(roundTripper http.RoundTripper) http.RoundTripper {
return &statusHandler{
healthCheckEndpoint: healthCheckEndpoint,
roundTripper: roundTripper,
}
}
}
// Decorate returns http.Roundtripper wraped with all passed decorators
func Decorate(roundTripper http.RoundTripper, decorators ...Decorator) http.RoundTripper {
for _, dec := range decorators {
roundTripper = dec(roundTripper)
}
return roundTripper
}