How to Set Timeouts on Network Connections in Go

Web
Configure Go network timeouts using http.Client.Timeout or net.Dialer.Timeout to prevent hanging connections.

Set timeouts on network connections in Go by configuring the Timeout field on http.Client or using context.WithTimeout for finer control.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

client := &http.Client{
    Timeout: 5 * time.Second,
}

req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com", nil)
if err != nil {
    // handle error
}
resp, err := client.Do(req)
if err != nil {
    // handle timeout or other error
}

For net.Dial, use net.Dialer with a Timeout field:

dialer := &net.Dialer{Timeout: 5 * time.Second}
conn, err := dialer.Dial("tcp", "example.com:80")
if err != nil {
    // handle error
}