diff --git a/httpclient/client.go b/httpclient/client.go index d4c818c..612e13c 100644 --- a/httpclient/client.go +++ b/httpclient/client.go @@ -145,6 +145,26 @@ outter: response.Body.Close() } + // Wait before retrying. + if i > 0 { + backoffTime := c.retrier.NextInterval(i - 1) + ctx, cancel := context.WithTimeout(context.Background(), backoffTime) + + select { + case <-ctx.Done(): + cancel() + + case <-request.Context().Done(): + cancel() + + multiErr.Push(request.Context().Err().Error()) + c.reportError(request, request.Context().Err()) + + // If the request context has already been cancelled, don't retry + break outter + } + } + c.reportRequestStart(request) var err error response, err = c.client.Do(request) @@ -166,23 +186,6 @@ outter: multiErr = &valkyrie.MultiError{} break } - - backoffTime := c.retrier.NextInterval(i) - ctx, cancel := context.WithTimeout(context.Background(), backoffTime) - - select { - case <-ctx.Done(): - cancel() - - case <-request.Context().Done(): - cancel() - - multiErr.Push(request.Context().Err().Error()) - c.reportError(request, request.Context().Err()) - - // If the request context has already been cancelled, don't retry - break outter - } } return response, multiErr.HasError() diff --git a/httpclient/client_test.go b/httpclient/client_test.go index e5f32ef..0e01dba 100644 --- a/httpclient/client_test.go +++ b/httpclient/client_test.go @@ -465,6 +465,7 @@ func TestHTTPClientDontRetryWhenContextIsCancelled(t *testing.T) { } w.WriteHeader(http.StatusInternalServerError) + w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{ "response": "something went wrong" }`)) } diff --git a/httpclient/options_test.go b/httpclient/options_test.go index b92ce71..2e93673 100644 --- a/httpclient/options_test.go +++ b/httpclient/options_test.go @@ -128,6 +128,5 @@ func ExampleWithRetrier() { // Output: retry attempt 0 // retry attempt 1 // retry attempt 2 - // retry attempt 3 // error }