-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
88 lines (78 loc) · 2.04 KB
/
Copy pathrequest.go
File metadata and controls
88 lines (78 loc) · 2.04 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
package begger
import (
"bytes"
"io"
"net/http"
"time"
"github.com/sirupsen/logrus"
)
type Request struct {
Client *http.Client
Components RequestComponents
Retry *RetryOptions
// If this is left as nil, the default is `time.Sleep` function.
// Otherwise, Custom implementation like time.Sleep function.
Sleeper Sleeper
// Optional logger instance
Logger *logrus.Logger
}
// WARNING: This method is not responsible for closing the `response body`.
func (r *Request) Do() (*http.Response, *Error) {
url := r.Components.Url.Get()
if r.Logger != nil {
r.Logger.Debugf("Url: %s", url)
}
var maxRetry int
var waitInterval time.Duration
var backoffRate float64
if r.Retry != nil {
maxRetry = r.Retry.MaxAttemptValue()
waitInterval = r.Retry.WaitIntervalValue()
backoffRate = r.Retry.BackoffRateValue()
}
// One for actual request, others for retry attemps.
maxRetry++
var body io.Reader
if len(r.Components.Body) != 0 {
body = bytes.NewBuffer(r.Components.Body)
} else {
body = nil
}
request, err := http.NewRequest(r.Components.HTTPMethod, url, body)
for key, value := range r.Components.Headers {
request.Header.Set(key, value)
}
var response *http.Response
waitBeforeRetry := waitInterval
for attempt := 0; attempt < maxRetry; attempt++ {
if attempt != 0 {
if r.Logger != nil {
r.Logger.Debugf("Retry attempt: %d | Wait: %+v", attempt, waitBeforeRetry)
}
if r.Sleeper == nil {
time.Sleep(waitBeforeRetry)
} else {
r.Sleeper.Sleep(waitBeforeRetry)
}
}
response, err = r.Client.Do(request)
if err == nil && response != nil {
break
}
if attempt != 0 {
// Multiply the "WaitInterval" with the "BackoffRate".
waitBeforeRetry = time.Duration(float64(waitBeforeRetry) * backoffRate)
}
}
if err != nil && response == nil {
return nil, &Error{
HTTPStatusCode: http.StatusInternalServerError,
StatusName: http.StatusText(http.StatusInternalServerError),
Message: err.Error(),
}
}
return response, nil
}
type Sleeper interface {
Sleep(d time.Duration)
}