-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry_request.go
63 lines (54 loc) · 1.67 KB
/
retry_request.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
package wrapper
import (
"bytes"
"io/ioutil"
"net/http"
"code.cloudfoundry.org/cli/api/cloudcontroller"
)
// RetryRequest is a wrapper that retries failed requests if they contain a 5XX
// status code.
type RetryRequest struct {
maxRetries int
connection cloudcontroller.Connection
}
// NewRetryRequest returns a pointer to a RetryRequest wrapper.
func NewRetryRequest(maxRetries int) *RetryRequest {
return &RetryRequest{
maxRetries: maxRetries,
}
}
// Wrap sets the connection in the RetryRequest and returns itself.
func (retry *RetryRequest) Wrap(innerconnection cloudcontroller.Connection) cloudcontroller.Connection {
retry.connection = innerconnection
return retry
}
// Make retries the request if it comes back with a 5XX status code.
func (retry *RetryRequest) Make(request *http.Request, passedResponse *cloudcontroller.Response) error {
var err error
var rawRequestBody []byte
if request.Body != nil {
rawRequestBody, err = ioutil.ReadAll(request.Body)
defer request.Body.Close()
if err != nil {
return err
}
}
for i := 0; i < retry.maxRetries+1; i += 1 {
if rawRequestBody != nil {
request.Body = ioutil.NopCloser(bytes.NewBuffer(rawRequestBody))
}
err = retry.connection.Make(request, passedResponse)
if err == nil {
return nil
}
if request.Method == http.MethodPost ||
passedResponse.HTTPResponse != nil &&
passedResponse.HTTPResponse.StatusCode != http.StatusInternalServerError &&
passedResponse.HTTPResponse.StatusCode != http.StatusBadGateway &&
passedResponse.HTTPResponse.StatusCode != http.StatusServiceUnavailable &&
passedResponse.HTTPResponse.StatusCode != http.StatusGatewayTimeout {
break
}
}
return err
}