-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
req.go
226 lines (196 loc) · 5.08 KB
/
req.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package httpc
import (
"compress/gzip"
"context"
"encoding/gob"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/influxdata/influxdb/v2"
"github.com/influxdata/influxdb/v2/kit/tracing"
)
const (
headerContentType = "Content-Type"
headerContentEncoding = "Content-Encoding"
)
// Req is a request type.
type Req struct {
client doer
req *http.Request
authFn func(*http.Request)
decodeFn func(*http.Response) error
respFn func(*http.Response) error
statusFn func(*http.Response) error
err error
}
// Accept sets the Accept header to the provided content type on the request.
func (r *Req) Accept(contentType string) *Req {
return r.Header("Accept", contentType)
}
// Auth sets the authorization for a request.
func (r *Req) Auth(authFn func(r *http.Request)) *Req {
if r.err != nil {
return r
}
r.authFn = authFn
return r
}
// ContentType sets the Content-Type header to the provided content type on the request.
func (r *Req) ContentType(contentType string) *Req {
return r.Header("Content-Type", contentType)
}
// Decode sets the decoding functionality for the request. All Decode calls are called
// after the status and response functions are called. Decoding will not happen if error
// encountered in the status check.
func (r *Req) Decode(fn func(resp *http.Response) error) *Req {
if r.err != nil {
return r
}
r.decodeFn = fn
return r
}
// DecodeGob sets the decoding functionality to decode gob for the request.
func (r *Req) DecodeGob(v interface{}) *Req {
return r.Decode(func(resp *http.Response) error {
r := decodeReader(resp.Body, resp.Header)
return gob.NewDecoder(r).Decode(v)
})
}
// DecodeJSON sets the decoding functionality to decode json for the request.
func (r *Req) DecodeJSON(v interface{}) *Req {
return r.Decode(func(resp *http.Response) error {
r := decodeReader(resp.Body, resp.Header)
return json.NewDecoder(r).Decode(v)
})
}
// Header adds the header to the http request.
func (r *Req) Header(k, v string) *Req {
if r.err != nil {
return r
}
r.req.Header.Add(k, v)
return r
}
// Headers adds all the headers to the http request.
func (r *Req) Headers(m map[string][]string) *Req {
if r.err != nil {
return r
}
for header, vals := range m {
if header == "" {
continue
}
for _, v := range vals {
r = r.Header(header, v)
}
}
return r
}
// QueryParams adds the query params to the http request.
func (r *Req) QueryParams(pairs ...[2]string) *Req {
if r.err != nil || len(pairs) == 0 {
return r
}
params := r.req.URL.Query()
for _, p := range pairs {
params.Add(p[0], p[1])
}
r.req.URL.RawQuery = params.Encode()
return r
}
// RespFn provides a means to inspect the entire http response. This function runs first
// before the status and decode functions are called.
func (r *Req) RespFn(fn func(*http.Response) error) *Req {
r.respFn = fn
return r
}
// StatusFn sets a status check function. This runs after the resp func
// but before the decode fn.
func (r *Req) StatusFn(fn func(*http.Response) error) *Req {
r.statusFn = fn
return r
}
// Do makes the HTTP request. Any errors that had been encountered in
// the lifetime of the Req type will be returned here first, in place of
// the call. This makes it safe to call Do at anytime.
func (r *Req) Do(ctx context.Context) error {
if r.err != nil {
return r.err
}
r.authFn(r.req)
// TODO(@jsteenb2): wrap do with retry/backoff policy.
return r.do(ctx)
}
func (r *Req) do(ctx context.Context) error {
span, ctx := tracing.StartSpanFromContextWithOperationName(ctx, r.req.URL.String())
defer span.Finish()
u := r.req.URL
span.LogKV(
"scheme", u.Scheme,
"host", u.Host,
"path", u.Path,
"query_params", u.Query().Encode(),
)
tracing.InjectToHTTPRequest(span, r.req)
resp, err := r.client.Do(r.req.WithContext(ctx))
if err != nil {
return err
}
defer func() {
io.Copy(ioutil.Discard, resp.Body) // drain body completely
resp.Body.Close()
}()
span.LogKV(
"response_code", resp.StatusCode,
"response_byte", resp.ContentLength,
)
if r.respFn != nil {
if err := r.respFn(resp); err != nil {
return err
}
}
if r.statusFn != nil {
if err := r.statusFn(resp); err != nil {
return err
}
}
if r.decodeFn != nil {
if err := r.decodeFn(resp); err != nil {
return &influxdb.Error{
Code: influxdb.EInvalid,
Err: err,
}
}
}
return nil
}
// StatusIn validates the status code matches one of the provided statuses.
func StatusIn(code int, rest ...int) func(*http.Response) error {
return func(resp *http.Response) error {
for _, code := range append(rest, code) {
if code == resp.StatusCode {
return nil
}
}
return fmt.Errorf("recieved unexpected status: %s %d", resp.Status, resp.StatusCode)
}
}
var encodingReaders = map[string]func(io.Reader) io.Reader{
"gzip": func(r io.Reader) io.Reader {
if gr, err := gzip.NewReader(r); err == nil {
return gr
}
return r
},
}
func decodeReader(r io.Reader, headers http.Header) io.Reader {
contentEncoding := strings.TrimSpace(headers.Get(headerContentEncoding))
fn, ok := encodingReaders[contentEncoding]
if ok {
return fn(r)
}
return r
}