Context in Real Go Programs

Use context in HTTP handlers and clients, with database/sql, and avoid the most common context mistakes.

Contexts matter most where your program talks to the outside world. This section shows the patterns for HTTP and databases and lists the mistakes that quietly break cancellation.

Context in HTTP Servers and Clients

Handlers use r.Context(), which is cancelled when the client disconnects. Outgoing requests use http.NewRequestWithContext.

Context with Database Queries

Use QueryContext, ExecContext and BeginTx so slow queries are cancelled with the request.

Common Context Mistakes

Discarded or early cancel, Background deep in code, nil contexts, contexts in structs and ignored ctx parameters.

Background in a handler:

context.Background() inside a handler means the work keeps running after the client leaves.

Summary

Start from the request's context, pass it to every call, and give every outgoing call a deadline.

Using Context in Go HTTP Servers and Clients

Use r.Context() in HTTP handlers to stop work when clients disconnect, add timeouts to outgoing requests with NewRequestWithContext, and pass values through middleware.

Using Context with Database Queries in Go

Pass context to database/sql with QueryContext, ExecContext and BeginTx so slow queries are cancelled, and handle the errors that result.

Common Go Context Mistakes

The context mistakes Go developers make most often, from lost cancel functions and nil contexts to storing contexts in structs, with the warnings and fixes for each.