Skip to content

Context (Ctx)

Ctx is a thin wrapper around *fiber.Ctx that adds request parsing, typed response helpers, user access, and i18n support. It embeds *fiber.Ctx, so all standard Fiber methods are available.

type Ctx struct {
*fiber.Ctx
}

Decodes the JSON request body into dst and validates it using struct tags.

type CreateUserDTO struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required,email"`
}
func (c *UserController) create(ctx *core.Ctx) error {
var dto CreateUserDTO
if err := ctx.ParseBody(&dto); err != nil {
return err // 400 if malformed JSON, 422 if validation fails
}
// dto is safe to use
return ctx.Created(dto)
}

Returns:

  • 400 Bad Request — malformed JSON
  • 422 Unprocessable Entity — validation failed (with []FieldError body)

Parses ?page and ?limit query parameters from the request.

q := ctx.ParsePagination()
// q.Page — default: 1
// q.Limit — default: 20, max: 100

See Pagination for full reference.

All helpers JSON-encode the body and set the appropriate Content-Type header.

Responds with 200 OK.

return ctx.OK(user)
return ctx.OK(map[string]string{"message": "success"})

Responds with 201 Created.

return ctx.Created(newUser)

Responds with 204 No Content (no body).

return ctx.NoContent()

Responds with 404 Not Found. Accepts an optional custom message.

return ctx.NotFound()
return ctx.NotFound("user not found")

Stores the authenticated user in the request context. Called from guard middleware.

ctx.SetUser(&AuthUser{ID: "123", Role: "admin"})

Returns the raw user value stored by SetUser.

raw := ctx.User()

Generic helper to extract the user as a specific type.

user, ok := core.UserAs[*AuthUser](ctx)
if !ok {
return core.Unauthorized("not authenticated")
}

Returns (zero, false) if the user was not set or the type assertion fails.

Extracts the preferred locale from the Accept-Language header. Returns "en" if the header is absent or empty.

locale := ctx.Lang() // e.g. "es", "pt-BR", "en"

Translates a key using the configured Translator. Falls back to the key itself if no translator is set or the key is not found.

msg := ctx.T("errors.user_not_found")
msg := ctx.T("welcome.message", username)

The translator is set on the app with app.SetTranslator(t). See Interfaces — Translator.

Since Ctx embeds *fiber.Ctx, all Fiber request methods are available:

ctx.Params("id") // URL parameter
ctx.Query("search") // query string value
ctx.Get("Authorization") // request header
ctx.IP() // client IP
ctx.Method() // HTTP method
ctx.Path() // request path
ctx.Context() // underlying context.Context (for service calls)
ctx.Locals("key", value) // read/write per-request values

See the Fiber documentation for the full list.