How do I use http.Client with timeouts and retries?

This guide provides an example of using the Go http.Client with timeouts and retries, helping developers to handle HTTP requests efficiently while ensuring their applications are robust and reliable.

Go, http.Client, timeouts, retries, HTTP requests, Go programming, Go language


package main

import (
    "fmt"
    "net/http"
    "time"
)

// createClient creates an http.Client with timeout settings
func createClient(timeout time.Duration) *http.Client {
    return &http.Client{
        Timeout: timeout,
    }
}

// makeRequest tries to make an HTTP GET request with retries
func makeRequest(client *http.Client, url string, retries int) (*http.Response, error) {
    var resp *http.Response
    var err error

    for i := 0; i < retries; i++ {
        resp, err = client.Get(url)
        if err == nil {
            return resp, nil
        }
        fmt.Printf("Attempt %d failed: %v\n", i+1, err)
        time.Sleep(2 * time.Second) // wait before retrying
    }

    return nil, fmt.Errorf("failed after %d attempts: %w", retries, err)
}

func main() {
    client := createClient(5 * time.Second) // 5 seconds timeout
    url := "https://example.com"
    retries := 3

    resp, err := makeRequest(client, url, retries)
    if err != nil {
        fmt.Printf("Error making request: %v\n", err)
        return
    }
    defer resp.Body.Close()

    fmt.Printf("Response status: %s\n", resp.Status)
}
    

Go http.Client timeouts retries HTTP requests Go programming Go language