The retry feature in the Requests library automatically attempts failed HTTP requests again based on certain conditions. This section explains how to set up and adjust these retry strategies for more dependable web interactions.
- Enhancing Reliability with Retries
- Configuring Retry Strategies
- Customizing Retry Conditions
- Setting Maximum Retry Attempts
To set up retries in a fluent, chainable manner, you can configure your client like so:
client := requests.Create(&requests.Config{
BaseURL: "https://api.example.com",
}).SetRetryStrategy(
requests.ExponentialBackoffStrategy(1*time.Second, 2, 30*time.Second),
).SetRetryIf(
requests.DefaultRetryIf,
).SetMaxRetries(3)
This setup ensures that your client is ready to handle transient failures gracefully.
For consistent delay intervals between retries:
client.SetRetryStrategy(requests.DefaultBackoffStrategy(5 * time.Second))
To increase delay intervals linearly with each retry attempt:
client.SetRetryStrategy(requests.LinearBackoffStrategy(1 * time.Second))
For exponential delay increases between attempts, with an option to cap the delay:
client.SetRetryStrategy(requests.ExponentialBackoffStrategy(1*time.Second, 2, 30*time.Second))
Define when retries should be attempted based on response status codes or errors:
client.SetRetryIf(func(req *http.Request, resp *http.Response, err error) bool {
return resp.StatusCode == http.StatusInternalServerError || err != nil
})
To limit the number of retries, use the SetMaxRetries
method:
client.SetMaxRetries(3)
This method allows you to specify the maximum number of attempts the client should make to execute a request successfully.