-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathfluent.go
275 lines (243 loc) · 6.2 KB
/
fluent.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// Fluent HTTP client for Golang. With timeout, retries and exponential back-off support.
package fluent
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"time"
"github.com/lafikl/backoff"
)
type Request struct {
header map[string]string
method string
json interface{}
jsonIsSet bool
url string
retry int
timeout time.Duration
body io.Reader
res *http.Response
err error
backoff *backoff.ExponentialBackOff
req *http.Request
proxy string
}
func (f *Request) newClient() *http.Client {
return &http.Client{Timeout: f.timeout}
}
func (f *Request) newRequest() (req *http.Request, err error) {
if f.jsonIsSet {
body, jsonErr := json.Marshal(f.json)
if jsonErr != nil {
return nil, jsonErr
}
req, err = http.NewRequest(f.method, f.url, bytes.NewReader(body))
} else {
req, err = http.NewRequest(f.method, f.url, f.body)
}
return
}
// Set the request URL
// You probably want to use the methods [Post, Get, Patch, Delete, Put]
func (f *Request) Url(url string) *Request {
f.url = url
return f
}
// Set the request Method
// You probably want to use the methods [Post, Get, Patch, Delete, Put]
func (f *Request) Method(method string) *Request {
f.method = method
return f
}
// This is a shorthand method that calls f.Method with `POST`
// and calls f.Url with the url you give to her
func (f *Request) Post(url string) *Request {
f.Url(url).Method("POST")
return f
}
// Same as f.Post but the method is `PUT`
func (f *Request) Put(url string) *Request {
f.Url(url).Method("PUT")
return f
}
// Same as f.Post but the method is `PATCH`
func (f *Request) Patch(url string) *Request {
f.Url(url).Method("PATCH")
return f
}
// Same as f.Post but the method is `GET`
func (f *Request) Get(url string) *Request {
f.Url(url).Method("GET")
return f
}
// Same as f.Post but the method is `DELETE`
func (f *Request) Delete(url string) *Request {
f.Url(url).Method("DELETE")
return f
}
// A handy method for sending json without needing to Marshal it yourself
// This method will override whatever you pass to f.Body
// And it sets the content-type to "application/json"
func (f *Request) Json(j interface{}) *Request {
f.json = j
f.jsonIsSet = true
f.SetHeader("Content-type", "application/json")
return f
}
// Whatever you pass to it will be passed to http.NewRequest
func (f *Request) Body(b io.Reader) *Request {
f.body = b
return f
}
// sets the header entries associated with key to the element value.
//
// It replaces any existing values associated with key.
func (f *Request) SetHeader(key, value string) *Request {
f.header[key] = value
return f
}
// Timeout specifies a time limit for requests made by this
// Client. The timeout includes connection time, any
// redirects, and reading the response body. The timer remains
// running after Get, Head, Post, or Do return and will
// interrupt reading of the Response.Body.
//
// A Timeout of zero means no timeout.
func (f *Request) Timeout(t time.Duration) *Request {
f.timeout = t
return f
}
// The initial interval for the request backoff operation.
//
// the default is 500 * time.Millisecond
//
// For more information http://godoc.org/github.com/cenkalti/backoff#ExponentialBackOff
func (f *Request) InitialInterval(t time.Duration) *Request {
f.backoff.InitialInterval = t
return f
}
// Set the Randomization factor for the backoff.
//
// the default is 0.5
//
// For more information http://godoc.org/github.com/cenkalti/backoff#ExponentialBackOff
func (f *Request) RandomizationFactor(rf float64) *Request {
f.backoff.RandomizationFactor = rf
return f
}
// Set the Multiplier for the backoff.
//
// The default is 1.5.
//
// For more information http://godoc.org/github.com/cenkalti/backoff#ExponentialBackOff
func (f *Request) Multiplier(m float64) *Request {
f.backoff.Multiplier = m
return f
}
// Set the Max Interval for the backoff.
//
// The default is 60 * time.Second
//
// For more information http://godoc.org/github.com/cenkalti/backoff#ExponentialBackOff
func (f *Request) MaxInterval(mi time.Duration) *Request {
f.backoff.MaxInterval = mi
return f
}
// Set the Max Elapsed Time for the backoff.
//
// The default is 15 * time.Minute.
//
// For more information http://godoc.org/github.com/cenkalti/backoff#ExponentialBackOff
func (f *Request) MaxElapsedTime(me time.Duration) *Request {
f.backoff.MaxElapsedTime = me
return f
}
// Set how many times to retry if the request
// timedout or the server returned 5xx response.
func (f *Request) Retry(r int) *Request {
f.retry = r
return f
}
// Set a HTTP proxy
func (f *Request) Proxy(p string) *Request {
f.proxy = p
return f
}
func doReq(f *Request, c *http.Client) error {
var reqErr error
f.req, reqErr = f.newRequest()
if reqErr != nil {
return reqErr
}
for k, v := range f.header {
f.req.Header.Set(k, v)
}
res, err := c.Do(f.req)
// if there's an error in the request
// then we just return whatever err we got
if err != nil {
f.err = err
return nil
}
if res != nil && res.StatusCode >= 500 && res.StatusCode <= 599 && f.retry > 0 {
f.retry--
return errors.New("Server Error")
}
if res != nil {
f.res = res
}
return nil
}
func (f *Request) operation(c *http.Client) func() error {
return func() error {
return doReq(f, c)
}
}
func (f *Request) do(c *http.Client) (*http.Response, error) {
err := doReq(f, c)
if err != nil {
op := f.operation(c)
err = backoff.Retry(op, f.backoff)
if err != nil {
return nil, err
}
}
// Check if has operation failed after the retries
if f.err != nil {
return nil, f.err
}
return f.res, err
}
// It will construct the client and the request, then send it
//
// This function has to be called as the last thing,
// after setting the other properties
func (f *Request) Send() (*http.Response, error) {
c := *http.DefaultClient
if f.timeout != 0 {
nc := f.newClient()
c = *nc
}
if f.proxy != "" {
proxyUrl, err := url.Parse(f.proxy)
if err != nil {
return nil, err
}
c.Transport = &http.Transport{
Proxy: http.ProxyURL(proxyUrl),
}
}
res, err := f.do(&c)
return res, err
}
// Create a new request
func New() *Request {
f := &Request{}
f.header = map[string]string{}
f.backoff = backoff.NewExponentialBackOff()
f.err = nil
return f
}