Go’sDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/go-chi/chi/llms.txt
Use this file to discover all available pages before exploring further.
context.Context is the backbone of chi’s request lifecycle. Every chi router stores its routing state — URL parameters, matched patterns, and the routing path — directly on the request context. Understanding how this works lets you write middleware and handlers that communicate cleanly without global state or function argument threading.
What is context.Context?
context.Context is a standard library interface that carries deadlines, cancellation signals, and request-scoped values across API boundaries and goroutines. It was introduced in Go 1.7 and is now used throughout the standard library (including net/http).
Every *http.Request carries a context accessible via r.Context(). You can derive a new context with additional values using context.WithValue, then attach it back to the request with r.WithContext(ctx).
context_basics.go
How chi stores routing state
chi reserves a single context key —chi.RouteCtxKey — to store its own *chi.Context on the request context. This routing context tracks everything chi needs during the routing lifecycle:
chi_context_struct.go
get_route_context.go
RouteContext is just a typed lookup:
route_context_impl.go
Accessing URL parameters
chi provides two convenience functions for reading URL parameters.chi.Context.URLParams stack:
url_param_lookup.go
URL parameters are accumulated as the request passes through nested
sub-routers. This means a sub-router can read parameters matched by a parent
router without any extra wiring.
Pattern: middleware loads a resource, handler reads it
The most common context pattern in chi is a middleware that resolves a URL parameter into a typed domain object and stores it on the context. Downstream handlers then read the typed value, never dealing with raw IDs or DB calls themselves.Always use a package-local struct type as the context key. This guarantees no collision with keys set by other packages (including chi itself or third-party middleware).
package main
// contextKey is an unexported type for context keys in this package.
type contextKey struct{ name string }
var articleCtxKey = &contextKey{"article"}
The middleware reads the
{articleID} URL parameter with chi.URLParam, fetches the resource, and stores it on the context using the typed key.func ArticleCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
articleID := chi.URLParam(r, "articleID")
article, err := dbGetArticle(articleID)
if err != nil {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
// Store the typed *Article on the context using the private key.
ctx := context.WithValue(r.Context(), articleCtxKey, article)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
The handler performs a single type assertion to retrieve the value. Because
ArticleCtx already validated the resource, the handler can focus purely on the response.func getArticle(w http.ResponseWriter, r *http.Request) {
article, ok := r.Context().Value(articleCtxKey).(*Article)
if !ok {
http.Error(w, http.StatusText(http.StatusUnprocessableEntity), http.StatusUnprocessableEntity)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(article)
}
Attach
ArticleCtx to the /{articleID} sub-router so it only runs when an article ID is present in the path.Full example: user authentication middleware
Here is a complete, self-contained example showing a user-loading middleware alongside a handler that reads the user from context:auth_middleware_example.go
Context cancellation and timeouts
chi’smiddleware.Timeout sets a deadline on the request context. When the deadline is exceeded, ctx.Done() is closed and ctx.Err() returns context.DeadlineExceeded. Long-running handlers should check for cancellation to avoid wasted work:
timeout_handler.go
Reading the full routing context
Beyond URL parameters,chi.Context exposes fields useful for instrumentation and logging:
routing_context_fields.go
| Field | Type | Description |
|---|---|---|
RoutePath | string | Remaining path for sub-router traversal (override only) |
RouteMethod | string | HTTP method of the current request |
URLParams | RouteParams | Stack of all captured {param} key/value pairs |
RoutePatterns | []string | Ordered list of all patterns matched across the router stack |