#Retrying HTTP Requests in Go with retry-go

Elliot Forbes Elliot Forbes · Dec 16, 2022 · 2 min read

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 a convenient way to retry HTTP requests in Go with configurable options and callbacks.

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.

Further Reading:

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