Skip to content

Commit

Permalink
Update xhttp retry
Browse files Browse the repository at this point in the history
  • Loading branch information
onanying committed Jan 15, 2024
1 parent e518bdc commit f56c368
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
26 changes: 24 additions & 2 deletions src/xutil/xhttp/request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func TestRequestError(t *testing.T) {
a.NotNil(err)
}

func TestDebugAndRetry(t *testing.T) {
func TestDebugAndRetryFail(t *testing.T) {
a := assert.New(t)

count := 0
Expand All @@ -67,7 +67,29 @@ func TestDebugAndRetry(t *testing.T) {
a.Equal(count, 2)
}

func TestDebugAndAbortRetry(t *testing.T) {
func TestDebugAndRetrySuccess(t *testing.T) {
a := assert.New(t)

count := 0
xhttp.DefaultOptions.DebugFunc = func(l *xhttp.Log) {
log.Printf("%+v %+v %+v %+v\n", l.Duration, l.Request, l.Response, l.Error)
count++
}

url := "https://aaaaa.com/"
retryIf := func(resp *xhttp.XResponse, err error) error {
if count == 1 {
return errors.New("the first request failed")
}
return nil
}
_, err := xhttp.Request("GET", url, xhttp.WithRetry(retryIf, retry.Attempts(3)))

a.Nil(err)
a.Equal(count, 2)
}

func TestDebugAndRetryAbort(t *testing.T) {
a := assert.New(t)

count := 0
Expand Down
11 changes: 10 additions & 1 deletion src/xutil/xhttp/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ func (t Error) Error() string {
return errors.Join(logWithNumber...).Error()
}

func (t Error) HasAbortRetry() bool {
for _, err := range t {
if errors.Is(err, ErrAbortRetry) {
return true
}
}
return false
}

func doRetry(opts *requestOptions, f func() (*XResponse, error)) (*XResponse, error) {
var resp *XResponse
var err error
Expand Down Expand Up @@ -47,7 +56,7 @@ func doRetry(opts *requestOptions, f func() (*XResponse, error)) (*XResponse, er
if err != nil {
return nil, err
}
if len(errorLog) > 0 {
if errorLog.HasAbortRetry() {
return nil, &errorLog
}
return resp, nil
Expand Down

0 comments on commit f56c368

Please sign in to comment.