1pub mod logs;
2mod default_headers;
3mod request_id;
4mod with_state;
5
6pub use default_headers::DefaultHeaders;
7pub use request_id::RequestId;
8pub use with_state::WithState;
9
10use std::future::Future;
11use std::sync::Arc;
12
13use crate::request::request::Request;
14use crate::response::response::Response;
15use crate::endpoint::DynEndpoint;
16
17#[crate::async_trait]
18pub trait Middleware: 'static + Send + Sync {
19    async fn handle<'a>(&'a self, req: Request, next: Next<'a>) -> Response;
20
21    fn name(&self) -> &str {
22        std::any::type_name::<Self>()
23    }
24}
25
26#[crate::async_trait]
27impl<F, Fut> Middleware for F
28    where
29        F: Fn(Request, Next<'_>) -> Fut + Send + Sync + 'static,
30        Fut: Future<Output=Response> + Send + 'static,
31{
32    async fn handle<'a>(&'a self, req: Request, next: Next<'a>) -> Response {
33        (self)(req, next).await
34    }
35}
36
37#[allow(missing_debug_implementations)]
38pub struct Next<'a> {
39    pub(crate) endpoint: &'a DynEndpoint,
40    pub(crate) next_middleware: &'a [Arc<dyn Middleware>],
41}
42
43impl<'a> Next<'a> {
44    pub async fn run(mut self, req: Request) -> Response {
45        if let Some((current, next)) = self.next_middleware.split_first() {
46            self.next_middleware = next;
47            current.handle(req, self).await
48        } else {
49            (self.endpoint).call(req).await
50        }
51    }
52}