Go HTTP Context Cancellation in Handlers
In this tutorial, you'll learn about Go HTTP Context Cancellation in Handlers. We cover key concepts, practical examples, and best practices.
Request context cancellation -- Handle client disconnections properly by checking context.Done() in long-running HTTP handlers to prevent wasted server resources.
The Problem
When a client disconnects, Go's http.Request context is cancelled. Handlers that ignore this continue processing database queries and API calls for a client that will never receive the response. This wastes server resources and degrades throughput.
Wrong
func slowHandler(w http.ResponseWriter, r *http.Request) {
time.Sleep(5 * time.Second)
w.Write([]byte("Done"))
}
Output:
$ curl --max-time 2 http://localhost:8080/slow
// Client disconnects after 2s, server works for 5s
Right
func slowHandler(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(5 * time.Second):
w.Write([]byte("Done"))
case <-r.Context().Done():
http.Error(w, "cancelled", 499)
}
}
Output:
$ curl --max-time 2 http://localhost:8080/slow
// cancelled
// Server stopped processing immediately
Prevention
- Always pass r.Context() to database queries using QueryContext
- Use select statements to listen for context cancellation
- Set http.Server timeouts (ReadTimeout, WriteTimeout, IdleTimeout)
- Log context cancellation for debugging client behavior
- Never ignore the context returned from http.Request
Common Mistakes with http context
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
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