Macro amiya::m[][src]

macro_rules! m {
    ($func: ident) => { ... };
    ($ctx: ident : $ex: ty => $body: block ) => { ... };
    ($ctx: ident => $body: block) => { ... };
    ($ctx: ident : $ex: ty => $body: expr) => { ... };
    ($ctx: ident => $body: expr) => { ... };
    ($ctx: ident : $ex: ty => $($body: tt)+) => { ... };
    ($ctx: ident => $($body: tt)+) => { ... };
}

Writer middleware easily.

It’s a macro to let you easily write middleware use closure and syntax like JavaScript’s arrow function, or convert a async fn to a middleware use the m!(async_func_name) syntax.

It returns a M instance, which implement Middleware trait.

Examples

Convert a async function to middleware

async fn response(mut ctx: Context<'_, ()>) -> Result {
    ctx.next().await?;
    ctx.resp.set_body("Hello world");
    Ok(())
}

let app = amiya::new().uses(m!(response));

Convert a block to middleware

Syntax: <Context parameter name> [: Extra data type] => { <your code> }

Default extra data type is (), same bellow.

//                                 | this `: ()` can be omitted
//                                 v
let app = amiya::new().uses(m!(ctx: () => {
    ctx.next().await?;
    ctx.resp.set_body("Hello world");
    Ok(())
}));

Convert a expr to middleware

Syntax: <Context parameter name> [: Extra data type] => <The expr>

async fn response(msg: &'static str, mut ctx: Context<'_, ()>) -> Result {
    ctx.next().await?;
    ctx.resp.set_body(msg);
    Ok(())
}

let app = amiya::new().uses(m!(ctx => response("Hello World", ctx).await));

Convert statements to middleware

Syntax: <Context parameter name> [: Extra data type] => <statements>

let app = amiya::new().uses(m!(ctx => ctx.resp.set_body("Hello World");));

Notice you do not return a value here, because a Ok(()) is auto added.

This is expand to:

ctx.resp.set_body("Hello World");
Ok(())