Skip to content

feat: RetryAttempt in PrepareRetry hook #258

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,8 +398,15 @@ type Backoff func(min, max time.Duration, attemptNum int, resp *http.Response) t
// attempted. If overriding this, be sure to close the body if needed.
type ErrorHandler func(resp *http.Response, err error, numTries int) (*http.Response, error)

// PrepareRetry is called before retry operation. It can be used for example to re-sign the request
type PrepareRetry func(req *http.Request) error
// PrepareRetry is called before the retry operation. It can be used, for example,
// to re-sign the request. After version 0.7.7, PrepareRetry takes the retryAttempt,
// a one-based counter that refers to the current retry attempt. The retryAttempt
// counter would help the server and clients make informed decisions. For example,
// - The client can send a request to a fallback host (server) after a certain number
// of retries.
// - The client can send the retry attempt in the request header, which would help
// the server to process the request in any special way if needed.
type PrepareRetry func(req *http.Request, retryAttempt int) error

// Client is used to make HTTP requests. It adds additional functionality
// like automatic retries to tolerate minor outages.
Expand Down Expand Up @@ -779,7 +786,7 @@ func (c *Client) Do(req *Request) (*http.Response, error) {
req.Request = &httpreq

if c.PrepareRetry != nil {
if err := c.PrepareRetry(req.Request); err != nil {
if err := c.PrepareRetry(req.Request, attempt); err != nil {
prepareErr = err
break
}
Expand Down
4 changes: 2 additions & 2 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -376,9 +376,9 @@ func TestClient_Do_WithPrepareRetry(t *testing.T) {
}

var prepareChecks int
client.PrepareRetry = func(req *http.Request) error {
client.PrepareRetry = func(req *http.Request, retryAttempt int) error {
prepareChecks++
req.Header.Set("foo", strconv.Itoa(prepareChecks))
req.Header.Set("foo", strconv.Itoa(retryAttempt))
return nil
}

Expand Down