Bug Description
DefaultCtx.Context() returns context.Background() by default when no user context has been set via SetContext(). This means any middleware or handler that calls c.Context() and passes it to I/O operations gets an uncancellable context by default.
How to Reproduce
Steps to reproduce the behavior:
- Create a handler that uses
c.Context() without calling SetContext() first
- Pass the context to a storage or HTTP operation
- The client disconnects
- The operation runs to completion because
context.Background() never signals cancellation
app.Get("/", func(c fiber.Ctx) error {
// c.Context() returns context.Background() by default
result, err := cache.GetWithContext(c.Context(), "key")
// This operation cannot be cancelled
})
Affected Code
ctx.go:129-138:
func (c *DefaultCtx) Context() context.Context {
if c.fasthttp == nil {
return context.Background()
}
if ctx, ok := c.fasthttp.UserValue(userContextKey).(context.Context); ok && ctx != nil {
return ctx
}
ctx := context.Background() // default fallback
c.SetContext(ctx) // cached β persists for the request
return ctx
}
Impact
Every middleware or handler that calls c.Context() without first calling c.SetContext() gets a context that cannot signal cancellation. This affects:
- Storage operations (
GetWithContext, SetWithContext)
- Database queries (
QueryContext, ExecContext)
- Outbound HTTP requests (
NewRequestWithContext)
- Any library accepting
context.Context
Expected Behavior
Consider adding middleware that automatically creates a proper context.Context from the request lifecycle (e.g., with client-disconnect detection). At minimum, document prominently that c.Context() returns context.Background() by default and that c.SetContext() should be called early in the middleware chain.
Related
Fiber Version
v3 (latest main branch)
Bug Description
DefaultCtx.Context()returnscontext.Background()by default when no user context has been set viaSetContext(). This means any middleware or handler that callsc.Context()and passes it to I/O operations gets an uncancellable context by default.How to Reproduce
Steps to reproduce the behavior:
c.Context()without callingSetContext()firstcontext.Background()never signals cancellationAffected Code
ctx.go:129-138:Impact
Every middleware or handler that calls
c.Context()without first callingc.SetContext()gets a context that cannot signal cancellation. This affects:GetWithContext,SetWithContext)QueryContext,ExecContext)NewRequestWithContext)context.ContextExpected Behavior
Consider adding middleware that automatically creates a proper
context.Contextfrom the request lifecycle (e.g., with client-disconnect detection). At minimum, document prominently thatc.Context()returnscontext.Background()by default and thatc.SetContext()should be called early in the middleware chain.Related
Done()returns nil (same root cause β fasthttp limitation)Fiber Version
v3 (latest main branch)