Using hashicorp go-retryablehttp
library (https://github.com/hashicorp/go-retryablehttp)
It retries automatically for all 5xx
code:
retryablehttp performs automatic retries under certain conditions. Mainly, if an error is returned by the client (connection errors, etc.), or if a 500-range response code is received (except 501), then a retry is invoked after a wait period. Otherwise, the response is returned and left to the caller to interpret.
Is that possible it retries on Request Timeout
, e.g. on 408
http status code just ootb?
or I should build some custom wrappers?
You can implement your own retry policy and pass it to the Client.CheckRetry field.
Doc ref:
Code ref:
The code might look like something similar to
package main
import (
"context"
"net/http"
"github.com/hashicorp/go-retryablehttp"
)
func main() {
retryClient := retryablehttp.NewClient()
retryClient.RetryMax = 10
retryClient.CheckRetry = func(ctx context.Context, resp *http.Response, err error) (bool, error) {
ok, e := retryablehttp.DefaultRetryPolicy(ctx, resp, err)
if !ok && resp.StatusCode == http.StatusRequestTimeout {
return true, nil
// return true for a retry,
// if e is nil,
// you might want to populate that error
// to propagate it.
// see https://github.com/hashicorp/go-retryablehttp/blob/02c1586c8f14be23e7eeb522f1094afbabf45e93/client.go#L673
}
return ok, e
}
}