Skip to content

Commit

Permalink
Update xhttp ErrAbortRetry
Browse files Browse the repository at this point in the history
  • Loading branch information
onanying committed Jan 12, 2024
1 parent b71231d commit 578b312
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
28 changes: 28 additions & 0 deletions src/xutil/xhttp/request_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package xhttp_test

import (
"errors"
"fmt"
"github.com/avast/retry-go"
"github.com/mix-go/xutil/xhttp"
Expand Down Expand Up @@ -62,3 +63,30 @@ func TestDebugAndRetry(t *testing.T) {
a.NotNil(err)
a.Contains(err.Error(), "attempts fail")
}

func TestDebugAndAbortRetry(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 err != nil {
return errors.Join(err, xhttp.ErrAbortRetry)
}
if resp.StatusCode != 200 {
return fmt.Errorf("invalid status_code: %d", resp.StatusCode)
}
return nil
}
resp, err := xhttp.Request("GET", url, xhttp.WithRetry(retryIf, retry.Attempts(2)))

a.Nil(resp)
a.NotNil(err)
a.Contains(err.Error(), "xhttp: abort further retries")
a.Equal(count, 1)
}
14 changes: 13 additions & 1 deletion src/xutil/xhttp/retry.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,28 @@
package xhttp

import (
"errors"
"github.com/avast/retry-go"
)

var ErrAbortRetry = errors.New("xhttp: abort further retries")

type RetryIfFunc func(*XResponse, error) error

func doRetry(opts *requestOptions, f func() (*XResponse, error)) (*XResponse, error) {
var resp *XResponse
var err error
var lastErr error
err = retry.Do(
func() error {
resp, err = f()
if opts.RetryIfFunc != nil {
return opts.RetryIfFunc(resp, err)
err := opts.RetryIfFunc(resp, err)
if err != nil && errors.Is(err, ErrAbortRetry) {
lastErr = err
return nil
}
return err
}
if err != nil {
return err
Expand All @@ -25,5 +34,8 @@ func doRetry(opts *requestOptions, f func() (*XResponse, error)) (*XResponse, er
if err != nil {
return nil, err
}
if lastErr != nil {
return nil, lastErr
}
return resp, nil
}

0 comments on commit 578b312

Please sign in to comment.