*mizu.Ctx β short for context. This is your primary interface for working with HTTP requests and responses. Understanding Ctx is essential for building any Mizu application.
What is Context?
In web development, context refers to all the information associated with a single HTTP request. When a user visits your website:- Their browser sends a request (URL, headers, body)
- Your server processes it and creates a response (status, headers, body)
- Various metadata is tracked (timing, request ID, user info)
Ctx object, giving you easy access to everything you need.
The
Ctx type is a thin wrapper around Goβs standard http.Request and http.ResponseWriter. It adds convenience methods while maintaining full compatibility with the standard library.The Mizu Ctx Wrapper
When a request arrives, Mizu creates aCtx that contains:
Creating Your First Handler with Context
http://localhost:3000/hello?name=Mizu and youβll see βHello, Mizu!β.
Accessing the Request
The request contains everything the client sent. Usec.Request() to access the underlying *http.Request:
Common Request Properties
Writing Responses
The response writer is how you send data back to the client. While Mizu provides convenient helper methods, you can also access the raw writer:Using Helper Methods (Recommended)
Mizu provides helper methods that handle common response patterns:The Request Logger
Each request has its own logger that automatically includes request context:Log Output Example
When using the default development logger:request_id is automatically added to help trace requests across log entries.
Working with Goβs context.Context
Every request includes acontext.Context that signals when the request should stop. This is essential for:
- Timeouts: Stop processing if it takes too long
- Cancellation: Stop if the client disconnects
- Value Passing: Store request-scoped data
Checking for Cancellation
Passing Context to Database Calls
Always pass the request context to database and external service calls:Request Timeouts
You can add timeouts to prevent slow requests from consuming resources:Working with Headers
Headers provide metadata about requests and responses:Reading Request Headers
Setting Response Headers
Common Headers
Storing Values in Context
Sometimes you need to pass data between middleware and handlers. Use context values:Setting Values in Middleware
Reading Values in Handlers
Helper Functions for Type Safety
Create helper functions to avoid repetitive type assertions:Context Best Practices
Doβs
Donβts
Testing with Context
When writing tests, you can create a test context:Testing with Context Values
Complete Example
Hereβs a complete example showing context usage in a real-world scenario:Summary
Whatβs Next
- Request - Learn more about reading request data
- Response - All the ways to send responses
- Middleware - Building request pipelines
- Error Handling - Handling errors gracefully