router!() { /* proc-macro */ }
Expand description

Macro for defining a router in submillisecond.

The syntax in this macro is aimed to be as simple and intuitive as possible.

Handlers

Handlers are routes with a HTTP method, path and handler.

A basic example would be:

router! {
    GET "/home" => home_handler
}

In this example, home_handler is a function we defined which implements Handler.

Multiple routes can be defined with handlers:

router! {
    GET "/" => index_handler
    GET "/about" => about_handler
    POST "/avatar" => avatar_handler
}

Methods

The supported methods are:

  • GET
  • POST
  • PUT
  • DELETE
  • HEAD
  • OPTIONS
  • PATCH

Sub-routers

Routers can be nested to create more complex routing.

Sub-routers are a similar syntax as handlers, except that they do not have a method prefix, and have curly braces after the =>.

router! {
    "/admin" => {
        GET "/dashboard" => admin_dashboard
        POST "/auth" => admin_auth
    }
}

The syntax in-between { and } is the same as the router macro itself.

Layers/middleware

Handlers which call submillisecond::RequestContext::next_handler are considered to be middleware.

Middleware can be used in the router macro using the with keyword.

router! {
    with global_logger;
}

Multiple middleware can be used with the array syntax.

router! {
    with [layer_one, layer_two];
}

In the examples above, the middleware is used on the whole router. Instead, we can also use middleware on a per-route basis.

router! {
    GET "/" with logger_layer => index_handler
}

When using guards, middleware should be placed after the if statement.

router! {
    GET "/admin" if IsAdmin with logger_layer => admin_handler
}

Guards

Guards can be used to protect routes.

The syntax is similar to a regular if statement, and is placed after the path of a route.

router! {
    GET "/admin" if IsAdmin => admin_handler
}

Syntax

RouterDefinition

{

    RouterMiddleware;

    RouterItem*

    RouterCatchAll

}

RouterItem

RouterMethodSTRING_LITERAL RouterIfStmtRouterMiddleware => RouterItemValue

RouterItemValue

IDENTIFIER | RouterDefinition

RouterMethod

GET | POST | PUT | DELETE | HEAD | OPTIONS | PATCH

RouterMiddleware

with RouterMiddlewareItem

RouterMiddlewareItem

IDENTIFIER | [ IDENTIFIER ]

RouterIfStmt

if Expression

RouterCatchAll

_ => RouterItemValue