Middleware

Trait Middleware 

Source
pub trait Middleware<'a, S = ()>:
    'static
    + Sync
    + Send {
    // Required method
    fn handle<'async_trait>(
        &'a self,
        ctx: &'a mut Context<S>,
        next: Next<'a>,
    ) -> Pin<Box<dyn Future<Output = Result> + 'async_trait>>
       where Self: 'async_trait,
             'a: '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§

Source

fn handle<'async_trait>( &'a self, ctx: &'a mut Context<S>, next: Next<'a>, ) -> Pin<Box<dyn Future<Output = Result> + 'async_trait>>
where Self: 'async_trait, 'a: 'async_trait,

Handle context and next, return status.

Implementations on Foreign Types§

Source§

impl<'a, S> Middleware<'a, S> for ()

blank middleware.

Source§

fn handle<'async_trait>( &'a self, _ctx: &'a mut Context<S>, next: Next<'a>, ) -> Pin<Box<dyn Future<Output = Result> + 'async_trait>>
where Self: 'async_trait, 'a: 'async_trait,

Implementors§

Source§

impl<'a, S> Middleware<'a, S> for Shared<S>
where S: 'static,

Source§

impl<'a, S, T, F> Middleware<'a, S> for T
where S: 'a, T: 'static + Send + Sync + Fn(&'a mut Context<S>, Next<'a>) -> F, F: 'a + Future<Output = Result>,

Source§

impl<'a, S, T, U> Middleware<'a, S> for Chain<T, U>
where U: Middleware<'a, S>, T: for<'b> Middleware<'b, S>,