Skip to content

Context (Ctx)

Ctx is a lightweight wrapper over *fiber.Ctx that adds request parsing, typed response helpers, user access, and i18n. Since it embeds *fiber.Ctx, all standard Fiber methods remain available.

type Ctx struct {
*fiber.Ctx
}

Decodes the JSON 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 *httpx.Ctx) error {
var dto CreateUserDTO
if err := ctx.ParseBody(&dto); err != nil {
return err // 400 if invalid 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 from the request.

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

See Pagination for the full reference.

All helpers serialize JSON and set the correct Content-Type header.

Responds with 200 OK.

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

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 message.

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

Stores the authenticated user in the request context. Used from middleware/guards.

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

Returns the raw value stored by SetUser.

raw := ctx.User()

Generic helper to extract the user with a specific type.

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

Returns (zero, false) if there is no user or the type assertion fails.

Extracts the preferred locale from Accept-Language. Returns "en" if no header.

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

Translates a key using the configured Translator. If no translator or the key doesn’t exist, returns the original key.

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

The translator is configured in the app with app.SetTranslator(t). See Contracts — Translator.

Since Ctx embeds *fiber.Ctx, you can use all Fiber methods:

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

See the Fiber documentation for the full list.