Skip to main content

rustio_core/
middleware.rs

1//! Around-style middleware.
2//!
3//! Each middleware is `async fn(Request, Next) -> Result<Response, Error>`
4//! and decides when to call [`Next::run`]. Short-circuiting (returning a
5//! response without calling next) is natural. [`Next`] is consumed by
6//! `run`, so the type system prevents calling it twice.
7
8use std::future::Future;
9use std::pin::Pin;
10use std::sync::Arc;
11
12use crate::error::Error;
13use crate::http::{Request, Response};
14
15type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
16
17pub type MiddlewareFn =
18    Arc<dyn Fn(Request, Next) -> BoxFuture<Result<Response, Error>> + Send + Sync>;
19
20pub struct Next {
21    inner: Box<dyn FnOnce(Request) -> BoxFuture<Result<Response, Error>> + Send>,
22}
23
24impl Next {
25    pub(crate) fn new(
26        inner: Box<dyn FnOnce(Request) -> BoxFuture<Result<Response, Error>> + Send>,
27    ) -> Self {
28        Self { inner }
29    }
30
31    pub async fn run(self, req: Request) -> Result<Response, Error> {
32        (self.inner)(req).await
33    }
34}