Context Timeout HTTP Client Request
Give outbound HTTP calls hard deadlines with context timeouts, propagating cancellation into DNS, connect, and body read phases.
Code
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
type Shipment struct {
ID string `json:"id"`
Status string `json:"status"`
}
func queryShipment(ctx context.Context, baseURL, id string) (*Shipment, error) {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel() // 必须释放计时器资源
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/shipments/"+id, nil)
if err != nil {
return nil, fmt.Errorf("build request: %w", err)
}
req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return nil, fmt.Errorf("shipment %s timed out after 3s: %w", id, err)
}
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
var shipment Shipment
if err := json.NewDecoder(resp.Body).Decode(&shipment); err != nil {
return nil, fmt.Errorf("decode body: %w", err)
}
return &shipment, nil
}
func main() {
s, err := queryShipment(context.Background(), "https://api.example.com", "sh-1")
fmt.Println(s, err)
}How the snippet works
Context Timeout HTTP Client Request keeps everything in the functions queryShipment and main.
Nothing falls through silently — 3 checkpoints test err != nil on the way through. Whatever happens in the body, the defer-ed call runs last on the way out.
Watch out for
- Self-contained — the only imports are ones the runtime already gives you.
- No panic path here — failures come back as
errorvalues that each caller must handle.
Applying it
The main signature is written as func queryShipment(ctx context.Context, baseURL, id string) (*Shipment, error)
main is the driver: it invokes queryShipment before returning.
Statements that matter most here
return nil, fmt.Errorf("shipment %s timed out after 3s: %w", id, err)
return nil, fmt.Errorf("request failed: %w", err)
return nil, fmt.Errorf("build request: %w", err)
Interactive Tools for This Topic
HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.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
- Does the snippet panic on failure?
- Through `error` values, not panics — the snippet checks `err != nil` at 3 sites.
- How do you run Context Timeout HTTP Client Request?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.