github.com/jghiloni/cli@v6.28.1-0.20170628223758-0ce05fe032a2+incompatible/api/cloudcontroller/wrapper/retry_request.go (about) 1 package wrapper 2 3 import ( 4 "net/http" 5 6 "code.cloudfoundry.org/cli/api/cloudcontroller" 7 "code.cloudfoundry.org/cli/api/cloudcontroller/ccerror" 8 ) 9 10 // RetryRequest is a wrapper that retries failed requests if they contain a 5XX 11 // status code. 12 type RetryRequest struct { 13 maxRetries int 14 connection cloudcontroller.Connection 15 } 16 17 // NewRetryRequest returns a pointer to a RetryRequest wrapper. 18 func NewRetryRequest(maxRetries int) *RetryRequest { 19 return &RetryRequest{ 20 maxRetries: maxRetries, 21 } 22 } 23 24 // Wrap sets the connection in the RetryRequest and returns itself. 25 func (retry *RetryRequest) Wrap(innerconnection cloudcontroller.Connection) cloudcontroller.Connection { 26 retry.connection = innerconnection 27 return retry 28 } 29 30 // Make retries the request if it comes back with a 5XX status code. 31 func (retry *RetryRequest) Make(request *cloudcontroller.Request, passedResponse *cloudcontroller.Response) error { 32 var err error 33 34 for i := 0; i < retry.maxRetries+1; i += 1 { 35 err = retry.connection.Make(request, passedResponse) 36 if err == nil { 37 return nil 38 } 39 40 // do not retry if the request method is POST, or not one of the following 41 // http status codes: 500, 502, 503, 504 42 if request.Method == http.MethodPost || 43 passedResponse.HTTPResponse != nil && 44 passedResponse.HTTPResponse.StatusCode != http.StatusInternalServerError && 45 passedResponse.HTTPResponse.StatusCode != http.StatusBadGateway && 46 passedResponse.HTTPResponse.StatusCode != http.StatusServiceUnavailable && 47 passedResponse.HTTPResponse.StatusCode != http.StatusGatewayTimeout { 48 break 49 } 50 51 // Reset the request body prior to the next retry 52 resetErr := request.ResetBody() 53 if resetErr != nil { 54 if _, ok := resetErr.(ccerror.PipeSeekError); ok { 55 return ccerror.PipeSeekError{Err: err} 56 } 57 return resetErr 58 } 59 } 60 return err 61 }