via/middleware/
middleware.rs

1use std::{future::Future, pin::Pin, sync::Arc};
2
3use super::Next;
4use crate::{response::IntoResponse, Request, Response, Result};
5
6pub(crate) type ArcMiddleware<State> = Arc<dyn Middleware<State>>;
7pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
8
9pub trait Middleware<State>: Send + Sync {
10    fn call(&self, request: Request<State>, next: Next<State>) -> BoxFuture<Result<Response>>;
11}
12
13impl<State, T, F> Middleware<State> for T
14where
15    T: Fn(Request<State>, Next<State>) -> F + Send + Sync + 'static,
16    F: Future + Send + 'static,
17    F::Output: IntoResponse,
18{
19    fn call(&self, request: Request<State>, next: Next<State>) -> BoxFuture<Result<Response>> {
20        let future = self(request, next);
21        Box::pin(async { future.await.into_response() })
22    }
23}