Context Timeout HTTP Client
Set timeouts on HTTP client requests using context for preventing hanging connections.
Code
package main
import ("context";"net/http";"time";"io")
func fetchWithTimeout(url string, timeout time.Duration) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil { return nil, err }
resp, err := http.DefaultClient.Do(req)
if err != nil { return nil, err }
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}Inside the snippet
The moving parts are the function fetchWithTimeout.
Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly. The function registers its cleanup up front with defer, so no exit path forgets it.
What to watch for
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Using it
The entry-point signature is func fetchWithTimeout(url string, timeout time.Duration) ([]byte, error)
Key statements
if err != nil { return nil, err }
ctx, cancel := context.WithTimeout(context.Background(), timeout)
return io.ReadAll(resp.Body)
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
FAQ
- What happens when a call fails?
- By return value: each fallible call hands back an `error`, checked at 2 places here.
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `fetchWithTimeout` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.