Route Constraints
Route constraints restrict which values a route parameter can match.
A constraint is added after the parameter name using a colon:
/users/{id:int}Mach currently supports string and int route constraints.
Integer Constraints
Section titled “Integer Constraints”The int constraint requires the route segment to contain an integer value.
app.mapGet("/users/{id:int}", [](mach::Context& context) { const int id = context.request.routeParam<int>("id"); return mach::ok(id);});For this route:
/users/42matches, while:
/users/alicedoes not.
Because the route requires an integer, a request containing a non-integer value does not match this endpoint.
String Constraints
Section titled “String Constraints”The string constraint requires the route segment to contain a string value.
app.mapGet("/users/{name:string}", [](mach::Context& context) { const auto name = context.request.routeParam("name"); return mach::ok(name);});The captured value can be retrieved as a string without specifying a template argument.
Constraints and Type Conversion
Section titled “Constraints and Type Conversion”Route constraints and routeParam<T>() serve different purposes.
Consider an unconstrained route:
app.mapGet("/users/{id}", [](mach::Context& context) { const int id = context.request.routeParam<int>("id"); return mach::ok(id);});The {id} parameter itself does not require the path segment to be an integer. The route can match a value such as alice, even though the endpoint later attempts to retrieve it as an int.
Adding an int constraint moves that requirement into routing:
app.mapGet("/users/{id:int}", [](mach::Context& context) { const int id = context.request.routeParam<int>("id"); return mach::ok(id);});Now, only values that satisfy the int constraint can match the endpoint.
Use constraints when the expected form of a route parameter should determine whether the route matches at all.
Next, you’ll learn how Mach chooses between multiple routes that could match the same request.