How to Use Context with HTTP Requests for Cancellation and Timeout

Web
Create a context with a timeout or cancel function and pass it to NewRequestWithContext to control HTTP request lifecycles.

Use context.WithTimeout or context.WithCancel to create a context, then pass it to http.NewRequestWithContext to enable automatic cancellation or timeout for HTTP requests.

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)
}