Trait roa_core::Middleware
source · [−]pub trait Middleware<'a, S = ()>: 'static + Sync + Send {
fn handle<'async_trait>(
&'a self,
ctx: &'a mut Context<S>,
next: Next<'a>
) -> Pin<Box<dyn Future<Output = Result> + 'async_trait>>
where
'a: 'async_trait,
Self: 'async_trait;
}
Expand description
Middleware
Build-in middlewares
- Functional middleware
A functional middleware is an async function with signature:
async fn(&mut Context, Next<'_>) -> Result
.
use roa_core::{App, Context, Next, Result};
async fn middleware(ctx: &mut Context, next: Next<'_>) -> Result {
next.await
}
let app = App::new().gate(middleware);
- Blank middleware
()
is a blank middleware, it just calls the next middleware or endpoint.
let app = roa_core::App::new().gate(());
Custom middleware
You can implement custom Middleware
for other types.
use roa_core::{App, Middleware, Context, Next, Result, async_trait};
use std::sync::Arc;
use std::time::Instant;
struct Logger;
#[async_trait(?Send)]
impl <'a> Middleware<'a> for Logger {
async fn handle(&'a self, ctx: &'a mut Context, next: Next<'a>) -> Result {
let start = Instant::now();
let result = next.await;
println!("time elapsed: {}ms", start.elapsed().as_millis());
result
}
}
let app = App::new().gate(Logger);
Required methods
Implementations on Foreign Types
blank middleware.