Context Timeout HTTP Client

Set timeouts on HTTP client requests using context for preventing hanging connections.

GoResilience

Code

gosnippet
12 lines
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 err before 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

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.