#Retrying HTTP Requests in Go with retry-go
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!
Continue Learning
How To Consume Data From A REST HTTP API With Go
Learn how to consume RESTful APIs in Go (Golang) with this step-by-step tutorial. Perfect for developers looking to master HTTP requests and JSON parsing in Go.
The Complete Guide to Building REST APIs in Go
Master building production-ready REST APIs in Go 1.26 with modern patterns, frameworks, and best practices for 2025-2026
Supercharge Your Go Tests Using Fake HTTP Services
Learn how to write reliable tests in Go by using fake HTTP services. This tutorial covers examples with httptest and the fakes library.
Handling Panics in Go
In this code snippet, we are going to be looking at how we can handle panics within our Go applications.