Context in handlers
Request.Context() is a context cancelled when the client disconnects, the request times out, or the server shuts down. Pass it into store calls and outgoing HTTP. Do not use it for work that must continue after the handler returns.
Detailed Explanation
The server derives a context per request and stores it on *http.Request. r.Context().Done() fires when the peer goes away. QueryContext, http.NewRequestWithContext, and your repository methods should take that context so a cancelled request does not keep a SQL query running.
Timeouts. Server.ReadTimeout / WriteTimeout / IdleTimeout bound the connection. For handler-level deadlines, ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second); defer cancel() around a specific call. Do not replace the request context entirely with Background unless you are starting detached work.
Detached work. A hook that must run after you return 202 should not use r.Context(). Use context.WithoutCancel(r.Context()) (keeps values, drops cancel) plus a new timeout, or context.Background() plus timeout. Document that the client will not wait.
Values. Middleware puts a request ID in the context. Handlers read it with the same key type. The request context is the right place for that, not for a DB pool.
What it costs. Ignoring the request context is wasted work and held connections. Using it for a background job is a cancelled job the moment the handler finishes — which looks like a Heisenbug.
Code Examples
package main
import (
"context"
"net/http"
"time"
)
func getUser(store interface {
Find(context.Context, string) error
}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := store.Find(ctx, r.PathValue("id")); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
}
func main() {}func detach(r *http.Request) (context.Context, context.CancelFunc) {
return context.WithTimeout(context.WithoutCancel(r.Context()), 30*time.Second)
}Common Gotchas
`WithTimeout(Background)` in a handler drops client disconnect
start from `r.Context()` unless the work is detached.
Always `defer cancel()` on the timeout you create
Always `defer cancel()` on the timeout you create