simple http client with a basic retry / back off strategy
- Default retry / back off strategy 1 seconds, 3 seconds, 5 seconds, 10 seconds
- Provide optional custom retry strategy
- Provide optional HTTP client
- Set default headers for every request
- Add additional headers for individual requests
- Response codes > 399 are treated as errors (fetch.APIError)
- demo dad jokes
fetch:=fetch.New()
varapiErr*fetch.APIErrorresp, err:=fetch.Get("https://icanhazdadjoke.com/", nil)
iferr!=nil {
iferrors.As(err, &apiErr) {
// non 2xx,3xx response// StatusCode: 400// StatusText: Bad Request// Message: ""fmt.PrintLn(apiErr)
}
// standard errorsos.Exit(1)
}headers:=map[string]string{
"Authorization": "Bearer boo"
}
fetch:=fetch.New()
resp, err:=fetch.Get("https://icanhazdadjoke.com/", headers)
iferr!=nil {
iferrors.As(err, &apiErr) {
// non 2xx,3xx response// StatusCode: 400// StatusText: Bad Request// Message: ""fmt.PrintLn(apiErr)
}
// standard errorsos.Exit(1)
}headers:=map[string]string{
"Authorization": "Bearer boo"
}
options:= fetch.Options{
DefaultHeaders=headers,
}
fetch:=fetch.New(options)
resp, err:=fetch.Get("https://icanhazdadjoke.com/", nil)
iferr!=nil {
iferrors.As(err, &apiErr) {
// non 2xx,3xx response// StatusCode: 400// StatusText: Bad Request// Message: ""fmt.PrintLn(apiErr)
}
// standard errorsos.Exit(1)
}Use Ctx if you want more granular control and the ability to cancel.
varapiErr*fetch.APIErrorctx, cancel:=context.WithCancel(context.Background())
defercancel()
resp, err:=client.PutCtx(ctx,url, bytes.NewReader([]byte(`{"hello": "world"}`)), nil)
iferr!=nil {
iferrors.is(err, context.Canceled) {
// Handle context cancelled
}
iferrors.As(err, &apiErr) {
fmt.Println("API Response error", apiErr)
}
// Handle non-API Error
}fetch:=fetch.New(WithOpts(
/** ... more options */WithRetryStrategy(&[]time.Duration{1, 2}),
))| option | description |
|---|---|
| WithDefaultRetryStrategy | Use default retry strategy |
| WithHeaders | Set default headers for every request |
| WithRetryStrategy | Provide custom retry strategy |
| WithHTTPClient | Provide custom http client |
feature requests being worked on will be added here