Retrying HTTP Requests in Go with retry-go

Elliot Forbes Elliot Forbes ⏰ 2 Minutes 📅 Dec 16, 2022

👋 Welcome Gophers! In this quick tutorial, we are going to be looking at how we can easily retry http requests in Go using the retry-go library.

Retrying Requests

The retry-go library is something that I’ve used in production environments just this past week and it is an incredibly convenient way to retry HTTP requests in Go.

Let’s have a quick look at how we can use this to achieve fame and fortune.

import "github.com/avast/retry-go"

func sendRequest() error {
    var resp *http.Response
    err := retry.Do(
        func() error {
            var err error
            resp, err = http.Get("http://www.example.com/")
            return err
        },
        retry.Attempts(3),
        retry.OnRetry(func(n uint, err error) {
            log.Printf("Retrying request after error: %v", err)
        }),
    )
    if err != nil {
        return err
    }
    defer resp.Body.Close()
    // do something with the response
    return nil
}

In this example, the retry.Do function retries the HTTP GET request up to three times. If the request fails, the OnRetry hook is called, which logs the error. If the request still fails after three attempts, the sendRequest function returns the error.

The retry-go library provides a number of options for customizing the retry behavior. For example, you can use the Delay option to specify a delay between retries, or the RetryIf option to specify a custom retry condition. You can find more information about these options in the library documentation.

Hopefully this quick article helps you in your own Go adventures!