Context Timeout HTTP Client Request

Give outbound HTTP calls hard deadlines with context timeouts, propagating cancellation into DNS, connect, and body read phases.

GoData Fetching

Code

gosnippet
46 lines
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 error values 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

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.