Middleware
Middleware behaves the same as middlewares in traditional web frameworks. It wraps around the next middleware or handler, access the request data, modify or alter the response data. The middleware ordering in the stack is first in last out.
To declare a middleware, use declare middleware
.
declare middleware print(label?: String)
Middleware implementation
To implement custom handlers, use server APIs. See:
- Namespace REFERENCE
- handler::Group REFERENCE
- Request REFERENCE
- Response REFERENCE
app.main_namespace().define_middleware("print", |arguments: Arguments| async move {
let label_str: String = arguments.get("label")?;
let label = Box::leak(Box::new(label_str)).as_str();
Ok(middleware_wrap_fn(move |ctx: Ctx, next: &'static dyn Next| async move {
println!("{}", label);
let res = next.call(ctx).await?;
return Ok(res);
}))
});
Installation
Middlewares can be applied to namespaces, while the middlewares stack inherit items from the parent namespace, too.
This code snippet demostrates how to install middlewares to a namespace's middleware stack.
middlewares [
middleware1(arg1: "arg1"),
middleware2
]