Go HTTP Client with Retry
Make HTTP requests in Go with retry logic, exponential backoff, context-based timeouts, connection pooling, and response decoding to typed structs using.
Code
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
func fetchWithRetry(url string, retries int) (*User, error) {
var lastErr error
for i := 0; i < retries; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
res, err := http.DefaultClient.Do(req)
cancel()
if err != nil { lastErr = err; time.Sleep(time.Duration(1<<i) * time.Second); continue }
defer res.Body.Close()
var u User
json.NewDecoder(res.Body).Decode(&u)
return &u, nil
}
return nil, lastErr
}What runs, in order
All of the logic lives in the function fetchWithRetry.
Repetition is confined to for i := 0; i < retries; i++ — the rest of the file is straight-line. Failures are values here: 1 site check err and decide instead of letting one propagate. The cleanup call is deferred to function exit — success, early return, and panic all covered.
Watch out for
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Putting it to use
The primary signature is func fetchWithRetry(url string, retries int) (*User, error)
Core lines
if err != nil { lastErr = err; time.Sleep(time.Duration(1<<i) * time.Second); continue }
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer res.Body.Close()
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
FAQ
- Is there exception handling?
- As returned `error` values — 1 site in the snippet check `err` before using other results.
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. Every import resolves inside the standard library — `context`, `encoding/json`, `fmt`. The file defines `fetchWithRetry` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.