Macro rouille::router
[−]
[src]
macro_rules! router { ($request:expr, $(($method:ident) ($($pat:tt)+) => $value:block,)* _ => $def:expr) => { ... }; (__check_pattern $url:ident $value:block /{$p:ident} $($rest:tt)*) => { ... }; (__check_pattern $url:ident $value:block /{$p:ident: $t:ty} $($rest:tt)*) => { ... }; (__check_pattern $url:ident $value:block /$p:ident $($rest:tt)*) => { ... }; (__check_pattern $url:ident $value:block - $($rest:tt)*) => { ... }; (__check_pattern $url:ident $value:block) => { ... }; (__check_pattern $url:ident $value:block /) => { ... }; (__check_pattern $url:ident $value:block $p:ident $($rest:tt)*) => { ... }; }
Equivalent to a match
expression but for routes.
Example
let _result = router!(request, // first route (GET) (/) => { 12 }, // second route (GET) (/hello) => { 43 * 7 }, // ... other routes here ... // default route _ => 5 );
Details
The macro will take each route one by one and execute the first one that matches, similar to a
match
language construct. The whole router!
expression then returns what the body
returns, therefore all the bodies must return the same type of data.
You can use parameters by putting them inside {}
:
(GET) (/{id}/foo) => { ... },
If you use parameters inside {}
, then a variable with the same name will be available in the
code in the body.
Each parameter gets parsed through the FromStr
trait. If the parsing fails, the route is
ignored. If you get an error because the type of the parameter couldn't be inferred, you can
also specify the type inside the brackets:
(GET) (/{id: u32}/foo) => { ... },
Some other things to note:
- The right of the
=>
must be a block (must be surrounded by{
and}
). - The pattern of the URL and the closure must be inside parentheses. This is to bypass limitations of Rust's macros system.
- The default handler (with
_
) must be present or will get a compilation error.