Skip to content

Go HTTP Context Cancellation in Handlers

DodaTech Updated 2026-06-24 1 min read

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

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. 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

**When is the request context cancelled?**

When the client disconnects, the request times out, or the server begins graceful shutdown.

Should I pass context to every DB call?

Yes. Use QueryContext, ExecContext, etc. so database operations stop when the client disconnects.

What is status 499?

Nginx-specific status for client-closed connection. Use it in your logs to track cancelled requests.


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