Go

http.Client with Timeout

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`http.DefaultClient` has no timeout — a hung server can hang your whole program forever. ALWAYS use a custom client with an explicit timeout for outbound requests.
Go
Raw
package main

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

var client = &http.Client{
    Timeout: 10 * time.Second,                 // total request timeout
    Transport: &http.Transport{
        MaxIdleConns:        100,
        MaxIdleConnsPerHost: 10,
        IdleConnTimeout:     90 * time.Second,
    },
}

func fetch(url string) (string, error) {
    resp, err := client.Get(url)
    if err != nil { return "", err }
    defer resp.Body.Close()
    body, err := io.ReadAll(resp.Body)
    if err != nil { return "", err }
    return string(body), nil
}

func main() {
    body, err := fetch("https://example.com")
    if err != nil {
        fmt.Println("error:", err); return
    }
    fmt.Println("got", len(body), "bytes")
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.