Skip to content

Repository files navigation

Fetch

simple http client with a basic retry / back off strategy

Features

  • 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)


Examples


fetch basic example

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)
}

fetch with headers

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)
}

fetch with default headers

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)
}

Cancelable HTTP calls

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
}


Using functional options



fetch:=fetch.New(WithOpts(
/** ... more options */WithRetryStrategy(&[]time.Duration{1, 2}),
))

Available options

optiondescription
WithDefaultRetryStrategyUse default retry strategy
WithHeadersSet default headers for every request
WithRetryStrategyProvide custom retry strategy
WithHTTPClientProvide custom http client


TODO

feature requests being worked on will be added here

About

Simple http client with backoff / retry built in and other features

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages