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()
var apiErr *fetch.APIError
resp, err := fetch.Get("https://icanhazdadjoke.com/", nil)
if err != nil {
if errors.As(err, &apiErr) {
// non 2xx,3xx response
// StatusCode: 400
// StatusText: Bad Request
// Message: ""
fmt.PrintLn(apiErr)
}
// standard errors
os.Exit(1)
}headers := map[string]string{
"Authorization": "Bearer boo"
}
fetch := fetch.New()
resp, err := fetch.Get("https://icanhazdadjoke.com/", headers)
if err != nil {
if errors.As(err, &apiErr) {
// non 2xx,3xx response
// StatusCode: 400
// StatusText: Bad Request
// Message: ""
fmt.PrintLn(apiErr)
}
// standard errors
os.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)
if err != nil {
if errors.As(err, &apiErr) {
// non 2xx,3xx response
// StatusCode: 400
// StatusText: Bad Request
// Message: ""
fmt.PrintLn(apiErr)
}
// standard errors
os.Exit(1)
}Use Ctx if you want more granular control and the ability to cancel.
var apiErr *fetch.APIError
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
resp, err := client.PutCtx(ctx,url, bytes.NewReader([]byte(`{"hello": "world"}`)), nil)
if err != nil {
if errors.is(err, context.Canceled) {
// Handle context cancelled
}
if errors.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