Route Patterns
Route patterns allow a single endpoint to match paths containing dynamic values.
In Mach, a route parameter is defined by placing its name inside curly braces:
/users/{id}Route Parameters
Section titled “Route Parameters”A route parameter captures the value of a path segment.
For example:
app.mapGet("/users/{id}", [](mach::Context& context) { const int id = context.request.routeParam<int>("id"); return mach::ok(id);});For a request to:
GET /users/42{id} captures 42.
The captured value can be accessed by name using routeParam():
const int id = context.request.routeParam<int>("id");The template argument determines the type Mach converts the captured value to.
Route parameters are not limited to numeric values. Strings can be retrieved without specifying a template argument:
app.mapGet("/users/{name}", [](mach::Context& context) { const auto name = context.request.routeParam("name"); return mach::ok(name);});For a request to:
GET /users/alicename contains "alice".
Multiple Parameters
Section titled “Multiple Parameters”A route can contain multiple parameters:
app.mapGet("/users/{userId}/posts/{postId}", [](mach::Context& context) { const int userId = context.request.routeParam<int>("userId"); const int postId = context.request.routeParam<int>("postId");
return mach::ok();});For a request to:
GET /users/42/posts/7userId contains 42 and postId contains 7.
Static and dynamic segments can be combined within the same route pattern.
Parameter Names
Section titled “Parameter Names”The name inside the braces identifies the route parameter:
/users/{userId}Use the same name when retrieving its value:
const int userId = context.request.routeParam<int>("userId");Choose descriptive parameter names that reflect the value represented by the path segment.
Unconstrained Parameters
Section titled “Unconstrained Parameters”A parameter without a constraint can match any valid path segment:
/users/{id}The route itself does not require {id} to contain a particular type of value.
The captured value can then be retrieved as the type your endpoint expects:
const int id = context.request.routeParam<int>("id");For example, /users/42 can match the unconstrained route above and the captured value can be converted to an int.
Constraints allow the expected form of the value to become part of the route itself.
Constrained Parameters
Section titled “Constrained Parameters”A constraint is added after the parameter name using a colon:
/users/{id:int}For example:
app.mapGet("/users/{id:int}", [](mach::Context& context) { const int id = context.request.routeParam<int>("id"); return mach::ok(id);});Unlike {id}, the {id:int} pattern only matches path segments that satisfy the int constraint.
Mach currently supports string and int route constraints.
Next, you’ll learn how route constraints control which values a route parameter can match.