Skip to content
Merged
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
11 changes: 9 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -471,9 +471,15 @@ func (c *Client) SetRetryAfter(callback RetryAfter) *Client {
return c
}

// SetRetryCount sets the maximum retry attempts before aborting.
// SetRetryCount sets the number of retries after the initial request before aborting.
// Negative values are treated as 0 (no retries).
func (c *Client) SetRetryCount(count int) *Client {
if count < 0 {
count = 0
}

c.retryCount = count

return c
}

Expand Down Expand Up @@ -519,7 +525,8 @@ func (c *Client) doRequest(ctx context.Context, method, endpoint string, params
err error
)

for range c.retryCount {
// retryCount controls the number of retries after the initial attempt
for range c.retryCount + 1 {
// createRequest seeks params.Body back to the start, so it's safe to retry.
req, err = c.createRequest(ctx, method, endpoint, params)
if err != nil {
Expand Down
32 changes: 32 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"os"
"reflect"
"strings"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -858,3 +859,34 @@ func TestEnableLogSanitization(t *testing.T) {
t.Error("expected Authorization header to appear in request log output")
}
}

func TestDoRequest_RetryCountZero_StillExecutes(t *testing.T) {
var called atomic.Bool

handler := func(w http.ResponseWriter, r *http.Request) {
called.Store(true)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"id":1}`))
}

server := httptest.NewServer(http.HandlerFunc(handler))
defer server.Close()

client := newTestClient(t, nil)
client.SetBaseURL(server.URL)
client.SetRetryCount(0)

type result struct {
ID int `json:"id"`
}

var got result

err := client.doRequest(context.Background(), http.MethodGet, "/test", requestParams{
Response: &got,
}, nil)
require.NoError(t, err, "doRequest should not return an error")
require.True(t, called.Load(), "server handler should have been called even with retryCount=0")
require.Equal(t, 1, got.ID, "response should have been decoded")
}