Execution Context
ExecutionContext is the request-scoped context.Context that flows through every layer of the pipeline. Learn its API, context tree rules, WithTimeout, and metadata management.
Execution Context
ExecutionContext is the runtime control plane for a single HTTP request or WebSocket connection. It embeds context.Context, carries typed metadata, and supports hierarchical SLA timeouts.
The Type
Because ExecutionContext embeds context.Context, it works transparently with any standard library or third-party code that accepts context.Context.
Construction
HTTP Request Context
The parent is r.Context() — the HTTP request's context. If the client disconnects, the cancellation propagates to exec and all derived contexts.
WebSocket Context
The parent is context.Background() — not the HTTP upgrade request's context. The upgrade context is cancelled when the handshake completes; basing a long-lived WS context on it would immediately cancel all WS work.
Context Tree
Rules
- Always pass
*ctx.ExecutionContextexplicitly as the first parameter to handlers, middleware, guards, and services. - Never store
*ExecutionContextin long-lived structs (modules, globals, or WS state). It is request-scoped and will be cancelled. - Always
defer cancel()for every context derived withWithTimeout.
WithTimeout
Derive a child context with an SLA deadline layered on top of the parent's deadline:
WithTimeout snapshot-copies the parent's metadata to the child, so child.Get(MetaUser) still works after the child is created.
Metadata
Setting Values
Reading Values
MustGet
For values that must be present (set by a prior middleware/guard), MustGet panics with a clear message if absent:
Well-Known Keys
Define your own typed keys to avoid string collisions:
Protocol
Check what transport owns this context:
GoSafe — Zero Goroutine Leaks
Never use go fn() inside a request handler. Use ctx.GoSafe instead:
How GoSafe Works
Key properties:
- Returns without spawning if
ctxis already cancelled. - Passes
ctxtofnso the goroutine canselectonctx.Done(). - Recovers panics and routes them to
errFn.
In Middleware and Guards
Access the execution context from ctx.Context via c.Exec: