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.

GoData Fetching

Code

snippet
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 err before 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

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.