How to Retry Failed HTTP Requests in Go

Web
Retry failed HTTP requests in Go by wrapping the client call in a loop with exponential backoff for transient errors.

Wrap your HTTP client in a retry loop that checks for transient errors and sleeps with exponential backoff before reissuing the request.

func DoWithRetry(client *http.Client, req *http.Request, maxRetries int) (*http.Response, error) {
	var resp *http.Response
	var err error
	for i := 0; i < maxRetries; i++ {
		resp, err = client.Do(req)
		if err == nil && resp.StatusCode < 500 {
			return resp, nil
		}
		if i < maxRetries-1 {
			time.Sleep(time.Duration(1<<uint(i)) * time.Second)
		}
	}
	return resp, err
}