Skip to content

code-gorilla-au/fetch

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

fetch with headers

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

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

Cancelable HTTP calls

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
	}


Using functional options



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

Available options

option description
WithDefaultRetryStrategy Use default retry strategy
WithHeaders Set default headers for every request
WithRetryStrategy Provide custom retry strategy
WithHTTPClient Provide 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

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •