improve retry feature for ghttp.Client

This commit is contained in:
John 2020-04-16 15:43:21 +08:00
parent 63f33d1d8c
commit 4f87668780
4 changed files with 15 additions and 17 deletions

View File

@ -1,19 +1,5 @@
package main
import "fmt"
// apiString is the type assert api for String.
type apiString interface {
String() string
}
func main() {
for i := 0; i < 10; i++ {
switch 1 {
case 1:
continue
}
fmt.Println(i)
}
}

View File

@ -124,3 +124,14 @@ func (c *Client) Ctx(ctx context.Context) *Client {
newClient.SetCtx(ctx)
return newClient
}
// Retry is a chaining function,
// which sets retry count and interval when failure for next request.
func (c *Client) Retry(retryCount int, retryInterval time.Duration) *Client {
newClient := c
if c.parent == nil {
newClient = c.Clone()
}
newClient.SetRetry(retryCount, retryInterval)
return c
}

View File

@ -28,7 +28,7 @@ type Client struct {
authPass string // HTTP basic authentication: pass.
browserMode bool // Whether auto saving and sending cookie content.
retryCount int // Retry count when request fails.
retryInterval int // Retry interval when request fails.
retryInterval time.Duration // Retry interval when request fails.
}
// NewClient creates and returns a new HTTP client object.
@ -143,7 +143,7 @@ func (c *Client) SetCtx(ctx context.Context) *Client {
}
// SetRetry sets retry count and interval.
func (c *Client) SetRetry(retryCount int, retryInterval int) *Client {
func (c *Client) SetRetry(retryCount int, retryInterval time.Duration) *Client {
c.retryCount = retryCount
c.retryInterval = retryInterval
return c

View File

@ -190,7 +190,7 @@ func (c *Client) DoRequest(method, url string, data ...interface{}) (resp *Clien
}
}
// It's necessary set the req.Host if you want to custom the host value of the request.
// It uses the "Host" value of the header.
// It uses the "Host" value from header if it's not set in the request.
if host := req.Header.Get("Host"); host != "" && req.Host == "" {
req.Host = host
}
@ -217,6 +217,7 @@ func (c *Client) DoRequest(method, url string, data ...interface{}) (resp *Clien
if r, err = c.Do(req); err != nil {
if c.retryCount > 0 {
c.retryCount--
time.Sleep(c.retryInterval)
} else {
return nil, err
}