Build context-aware HTTP requests
Build context-aware HTTP requests
Use http.NewRequestWithContext to construct a request with an explicit method, URL, body and context. Construction does not send anything. Client.Do performs the exchange. A request context controls connection acquisition, sending, and reading the response, so keep its cancellation function alive until body processing is complete.
package main
import ( "context" "fmt" "io" "net/http" "net/http/httptest" "time")
func check(err error) { if err != nil { panic(err) }}func fixture(h http.HandlerFunc) (*httptest.Server, *http.Client) { s := httptest.NewServer(h) c := s.Client() c.Timeout = 2 * time.Second return s, c}func main() { s, c := fixture(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, r.Header.Get("X-Task")) }) defer s.Close() ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() req, e := http.NewRequestWithContext(ctx, http.MethodGet, s.URL, nil) check(e) req.Header.Set("X-Task", "report") res, e := c.Do(req) check(e) defer res.Body.Close() b, e := io.ReadAll(res.Body) check(e) fmt.Println(string(b))}A nil body is appropriate for this GET. Set headers before Do; do not mutate a request concurrently while it is in use. The deadline covers the complete operation, not just request construction. The request URL here is fixed by the fixture; production clients must constrain untrusted destinations.
Expected output:
reportObserve cancellation
package main
import ( "context" "errors" "fmt" "net/http" "net/http/httptest" "time")
func check(err error) { if err != nil { panic(err) }}func fixture(h http.HandlerFunc) (*httptest.Server, *http.Client) { s := httptest.NewServer(h) c := s.Client() c.Timeout = 2 * time.Second return s, c}func main() { s, c := fixture(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) }) defer s.Close() ctx, cancel := context.WithCancel(context.Background()) cancel() req, e := http.NewRequestWithContext(ctx, http.MethodGet, s.URL, nil) check(e) res, e := c.Do(req) if res != nil { res.Body.Close() } fmt.Println(errors.Is(e, context.Canceled))}The standard transport rejects this canceled operation. Do returns an error typically wrapped in url.Error; errors.Is checks the cause rather than matching message text. Cancellation does not establish whether an already transmitted request changed server state. Avoid retrying a mutation simply because the client canceled.
Expected output:
trueTry it locally
Send a POST with body "blue" and a one-second context to a local handler that echoes the body; print blue.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP clients 02: Build context-aware HTTP requests
Check the lesson objective before moving on.
When does NewRequestWithContext send data?
When should the request context remain valid?