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
}