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.

Go Data 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
}