Context
Ctx is the request/response context passed to every handler. It provides methods for reading request data and writing responses. Contexts are pooled and reused for zero-allocation on the hot path.
Request Methods
Path
func (c *Ctx) Path() stringReturns the request path.
Method
func (c *Ctx) Method() stringReturns the HTTP method (GET, POST, etc.).
Param
func (c *Ctx) Param(key string) stringReturns a route parameter value.
// Route: /users/:id
app.Get("/users/:id", func(c *kruda.Ctx) error {
id := c.Param("id")
return c.Text("User: " + id)
})ParamInt
func (c *Ctx) ParamInt(name string) (int, error)Returns a route parameter as an integer.
Query
func (c *Ctx) Query(name string, def ...string) stringReturns a query string parameter value. Optional default value.
// GET /search?q=kruda&page=1
q := c.Query("q") // "kruda"
page := c.Query("page") // "1"
sort := c.Query("sort", "asc") // "asc" (default)QueryInt
func (c *Ctx) QueryInt(name string, def ...int) intReturns a query parameter as an integer with optional default.
Header
func (c *Ctx) Header(key string) stringReturns a request header value.
token := c.Header("Authorization")
contentType := c.Header("Content-Type")Cookie
func (c *Ctx) Cookie(name string) stringReturns a request cookie value by name.
IP
func (c *Ctx) IP() stringReturns the client IP address. Respects X-Forwarded-For / X-Real-IP only when WithTrustProxy(true) is set.
Bind
func (c *Ctx) Bind(v any) errorParses the request body as JSON into the given value.
var user User
if err := c.Bind(&user); err != nil {
return kruda.NewError(400, "Invalid JSON")
}BodyBytes
func (c *Ctx) BodyBytes() ([]byte, error)Returns the raw request body as bytes.
BodyString
func (c *Ctx) BodyString() stringReturns the request body as a string.
Response Methods
JSON
func (c *Ctx) JSON(v any) errorSends a JSON response. Set status code with Status() before calling.
return c.JSON(user) // 200 by default
return c.Status(201).JSON(user) // 201 CreatedText
func (c *Ctx) Text(s string) errorSends a plain text response.
return c.Text("Hello, World!")
return c.Status(200).Text("OK")HTML
func (c *Ctx) HTML(html string) errorSends an HTML response.
Status
func (c *Ctx) Status(code int) *CtxSets the response status code. Chainable.
return c.Status(201).JSON(user)StatusCode
func (c *Ctx) StatusCode() intReturns the current response status code.
NoContent
func (c *Ctx) NoContent() errorSends a 204 No Content response.
File
func (c *Ctx) File(path string) errorServes a file. Requires net/http transport.
Stream
func (c *Ctx) Stream(reader io.Reader) errorStreams a response from a reader.
SetHeader
func (c *Ctx) SetHeader(key, value string) *CtxSets a response header. CRLF characters in values are automatically stripped. Invalid header keys are silently skipped. Chainable.
c.SetHeader("X-Custom", "value")AddHeader
func (c *Ctx) AddHeader(key, value string) *CtxAdds a response header (allows multiple values for the same key). Chainable.
SetCookie
func (c *Ctx) SetCookie(cookie *Cookie) *CtxSets a response cookie. Uses kruda.Cookie (not http.Cookie). Cookie values are sanitized. Chainable.
c.SetCookie(&kruda.Cookie{
Name: "session",
Value: "abc123",
Path: "/",
})Redirect
func (c *Ctx) Redirect(url string, code ...int) errorSends a redirect response. Default status is 302.
return c.Redirect("/login") // 302
return c.Redirect("/new", 301) // 301Request-Scoped Storage
Set / Get
func (c *Ctx) Set(key string, value any)
func (c *Ctx) Get(key string) anyStore and retrieve request-scoped values.
Provide
func (c *Ctx) Provide(key string, value any)Provides a value for request-scoped DI resolution.
Middleware Control
Next
func (c *Ctx) Next() errorCalls the next handler in the middleware chain.
func LogMiddleware(c *kruda.Ctx) error {
start := time.Now()
err := c.Next()
slog.Info("request", "path", c.Path(), "duration", time.Since(start))
return err
}Context & Logging
Context
func (c *Ctx) Context() context.Context
func (c *Ctx) SetContext(ctx context.Context)Access or replace the underlying context.Context.
Log
func (c *Ctx) Log() *slog.LoggerReturns a request-scoped logger with request metadata.
Timing
MarkStart / Latency
func (c *Ctx) MarkStart()
func (c *Ctx) Latency() time.DurationTrack request latency (used by Logger middleware).
SSE
SSE
func (c *Ctx) SSE(fn func(*SSEStream) error) errorStarts a Server-Sent Events stream.
Method Chaining
Response methods return *Ctx for fluent chaining:
return c.Status(200).
SetHeader("X-Request-ID", reqID).
SetHeader("Cache-Control", "no-cache").
JSON(data)