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.

Here is an example usage:

let _result = router!(request,
    // first route
    (GET) (/) => {
        12
    },

    // ... other routes here ...

    // default route
    _ => 5
);

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 closure returns, therefore they must all return the same type.

You can use parameters by putting them inside {}:

(GET) (/{id}/foo) => {
    ...
},

If you use parameters inside {}, then a field with the same name must exist in the closure's parameters list. The parameters do not need be in the same order.

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.