Ctx interface (Context) provides methods for handling HTTP requests and responses. It’s the most important parameter passed to route handlers and middleware.
What is Ctx?
The Ctx object encapsulates the HTTP request and response, providing methods to:- Read request data (headers, body, parameters)
- Send responses (JSON, HTML, files)
- Set response headers and status codes
- Access request metadata
Request Methods
Reading Parameters
Access URL parameters defined in routes:Query Strings
Retrieve query parameters from the URL:Request Headers
Read request headers:Request Body
Parse request body in various formats:Cookies
Read and write cookies:Response Methods
Sending Text
Sending JSON
Setting Status Codes
Setting Headers
Sending Files
Redirects
Context Metadata
Request Information
Request Context
Access the standardcontext.Context:
Locals Storage
Store request-scoped data:Zero-Allocation Patterns
Fiber is designed for performance with zero-allocation in mind:Immutable vs Mutable
By default, values are mutable (zero-allocation) and only valid within the handler:Immutable mode for safe concurrent access:
Making Copies
Manually copy values when needed:Advanced Features
Request Binding
Bind request data to structs:Format Negotiation
Send different responses based on Accept header:MultipartForm
Handle file uploads:Context Lifecycle
The Ctx object is pooled and reused for performance:Best Practices
Don't store Ctx references
Don't store Ctx references
Never store the Ctx object itself - it’s pooled and reused.
Use Locals for request-scoped data
Use Locals for request-scoped data
Store data that should be shared between middleware and handlers using Locals.
Enable Immutable for goroutines
Enable Immutable for goroutines
If you need to use Ctx values in goroutines, enable Immutable mode.
Check errors from Bind methods
Check errors from Bind methods
Always validate the error returned from binding methods.
See Also
Routing
Define routes and access parameters
Middleware
Process requests with middleware
Error Handling
Handle errors in handlers
Request Binding
Bind request data to structs