HTTP Context
Discover the CaesarCtx
struct and its myriad of methods that make handling web requests a breeze in Caesar.
Overview
The CaesarCtx
struct is a critical component in the Caesar framework. It acts as a wrapper around the http.ResponseWriter
and http.Request
objects, providing additional methods to facilitate common tasks such as rendering templates, sending JSON responses, and handling form validation.
CaesarCtx Methods and Their Usages
Let's explore the rich set of methods provided by CaesarCtx
and understand how you can leverage them to build robust web applications.
Render
Usage
Use Render
to render templating components directly to the response.
if err := ctx.Render(myComponent); err != nil {
// handle error
}
Ideal for when you want to dynamically generate HTML using templating engines.
SendJSON
Usage
Use SendJSON
to send a JSON response, optionally with a custom status code.
if err := ctx.SendJSON(data); err != nil {
// handle error
}
if err := ctx.SendJSON(data, http.StatusCreated); err != nil {
// handle error
}
Perfect for API endpoints that return JSON data.
SendText
Usage
Use SendText
to send plain text responses.
if err := ctx.SendText("Hello, World!"); err != nil {
// handle error
}
if err := ctx.SendText("Internal Server Error", http.StatusInternalServerError); err != nil {
// handle error
}
Great for sending simple text responses or messages.
Context
Usage
Use Context
to get the request's context for further propagation.
ctx := context.WithValue(ctx.Context(), key, value)
Useful for managing request-scoped values and cancellations.
WithStatus
Usage
Use WithStatus
to set the HTTP status code for the response.
ctx.WithStatus(http.StatusBadRequest).SendText("Bad Request")
Handy when you need to explicitly set the HTTP status.
PathValue
Usage
Use PathValue
to retrieve path parameters from the request URL.
id := ctx.PathValue("id")
Essential for accessing dynamic segments in route URLs.
DecodeJSON
Usage
Use DecodeJSON
to parse the request body JSON into a struct.
if err := ctx.DecodeJSON(&data); err != nil {
// handle error
}
Ideal for handling JSON payloads in POST or PUT requests.
Redirect
Usage
Use Redirect
to redirect the client to another URL.
if err := ctx.Redirect("/new-location"); err != nil {
// handle error
}
Perfect for redirecting after successful form submissions or POST requests.
RedirectBack
Usage
Use RedirectBack
to send the client back to the previous page.
if err := ctx.RedirectBack(); err != nil {
// handle error
}
Great for handling "back" actions in web applications.
Validate
Usage
Use Validate
to validate the request body or form data.
data, errors, ok := core.Validate[MyStruct](ctx)
if !ok {
// handle validation errors
}
Crucial for enforcing data integrity and validating user input.
SetHeader
Usage
Use SetHeader
to set an HTTP header in the response.
ctx.SetHeader("Content-Type", "application/json")
Essential for customizing response headers.
GetHeader
Usage
Use GetHeader
to retrieve a header value from the request.
authHeader := ctx.GetHeader("Authorization")
Helpful for accessing request headers, especially for authentication.
Next
Usage
Use Next
to call the next handler in the middleware chain.
ctx.Next()
Vital for middleware chaining in your application.
WantsJSON
Usage
Use WantsJSON
to check if the client prefers JSON responses.
if ctx.WantsJSON() {
ctx.SendJSON(data)
} else {
ctx.SendText("Default text response")
}
Useful for content negotiation based on client preferences.
SetSSEHeaders
Usage
Use SetSSEHeaders
to set necessary headers for Server-Sent Events.
ctx.SetSSEHeaders()
Fundamental for applications that use real-time updates or server-sent events.
SendSSE
Usage
Use SendSSE
to send a Server-Sent Event to the client.
if err := ctx.SendSSE("event-name", "event-data"); err != nil {
// handle error
}
Excellent for pushing real-time updates to the client.
Conclusion
The CaesarCtx
struct simplifies many tasks when handling web requests in Caesar. Whether you need to send JSON, render a template, validate form data, or handle server-sent events, CaesarCtx
has got you covered.
Understanding CaesarCtx
empowers you to handle HTTP requests with finesse and elegance. So go ahead, take CaesarCtx
for a spin, and let it drive your web application to greatness!
Happy coding with Caesar! 🍕