[][src]Trait roa_core::Middleware

pub trait Middleware<'a, S>: 'static + Sync + Send {
#[must_use]    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
; }

Middleware

There are two kinds of middlewares, the one is functional middlewares, the another is trait middlewares.

Functional Middlewares

A normal functional middleware is an object implements Fn trait:

use roa_core::{Context, Next, Result, Middleware};
use std::future::Future;

fn is_middleware<S>(middleware: impl for<'a> Middleware<'a, S>) {
}

async fn middleware(ctx: &mut Context<()>, next: Next<'_>) -> Result {
    Ok(())
}

is_middleware(middleware);

Closures are also supported, but feature(async_closure) is required:

Trait Middlewares

A trait middleware is an object implementing trait Middleware.

use roa_core::{Middleware, Context, Next, Result, async_trait};
use async_std::sync::Arc;
use std::time::Instant;

fn is_middleware<S>(middleware: impl for<'a> Middleware<'a, S>) {}

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
    }
}

is_middleware(Logger);

Required methods

#[must_use]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, 

Handle context and next, then return a future to get status.

Loading content...

Implementations on Foreign Types

impl<'a, S> Middleware<'a, S> for ()[src]

Fake middleware.

Loading content...

Implementors

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

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>, 
[src]

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

Loading content...