Route Constraints: Validation Before Your Handler Runs
ยท 5 min read
Almost every REST API has a handler that starts like this:
app.Get("/users/:id", func(c fiber.Ctx) error {
id, err := strconv.Atoi(c.Params("id"))
if err != nil {
return fiber.ErrBadRequest
}
// ... finally, the actual logic
})
Three lines of ceremony before the handler does anything useful, repeated in every handler that takes a numeric parameter. Fiber has a feature that moves this check into the router itself: route constraints. Declare the parameter as :id<int> and the route simply does not match for /users/abc. Your handler only ever sees values that passed the check.
Constraints arrived back in v2.37 and were inspired by .NET Core routing. They remain one of the least-known routing features, which is a shame, because they remove boilerplate exactly where it accumulates fastest.
