Go Context: HTTP Request Cancellation
In this tutorial, you'll learn about Go Context: HTTP Request Cancellation. We cover key concepts, practical examples, and best practices.
HTTP request with context -- Use http.NewRequestWithContext to create cancellable HTTP requests.
The Problem
http.Get and http.Post do not accept contexts. Use http.NewRequestWithContext to create requests that respect cancellation.
Wrong
resp, err := http.Get("https://api.example.com/data")
Output:
// No context. Request cannot be cancelled or timeout.
Right
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", "https://api.example.com/data", nil)
if err != nil { log.Fatal(err) }
resp, err := http.DefaultClient.Do(req)
Output:
// Request cancelled after 5 seconds or when context is done
Prevention
- Use NewRequestWithContext for cancellable HTTP
- Combine with http.Client timeout for defense in depth
- Context cancels the request body download
- Pass context through the call chain
- Check resp.Body.Close() honours context for streaming
Common Mistakes with context http request
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro