How to Use Context with HTTP Requests in Go

Pass a context created with WithTimeout or WithCancel to NewRequestWithContext to control HTTP request deadlines.

Use context.WithTimeout or context.WithCancel to create a context, then pass it to http.NewRequestWithContext to ensure the request respects the deadline or cancellation signal.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

req, err := http.NewRequestWithContext(ctx, "GET", "https://example.com", nil)
if err != nil {
    log.Fatal(err)
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
    log.Fatal(err)
}