mincat_core/
middleware.rs

1use std::future::Future;
2
3use crate::{
4    next::Next,
5    request::Request,
6    response::{IntoResponse, Response},
7};
8
9#[async_trait::async_trait]
10pub trait Middleware: Send + Sync {
11    async fn call(self: Box<Self>, request: Request, next: Next) -> Response;
12
13    fn clone_box(&self) -> Box<dyn Middleware>;
14}
15
16impl Clone for Box<dyn Middleware> {
17    fn clone(&self) -> Self {
18        self.clone_box()
19    }
20}
21
22pub struct FuncMiddleware<Func>(Func)
23where
24    Func: MiddlewareFunc;
25
26impl<Func> FuncMiddleware<Func>
27where
28    Func: MiddlewareFunc,
29{
30    pub fn from_fn(func: Func) -> Self {
31        FuncMiddleware(func)
32    }
33}
34
35#[async_trait::async_trait]
36impl<Func> Middleware for FuncMiddleware<Func>
37where
38    Func: MiddlewareFunc,
39{
40    async fn call(self: Box<Self>, request: Request, next: Next) -> Response {
41        self.0.call(request, next).await
42    }
43
44    fn clone_box(&self) -> Box<dyn Middleware> {
45        Box::new(FuncMiddleware(self.0.clone()))
46    }
47}
48
49#[async_trait::async_trait]
50pub trait MiddlewareFunc: Clone + Send + Sync + 'static {
51    async fn call(self, request: Request, next: Next) -> Response;
52}
53
54#[async_trait::async_trait]
55impl<Func, Res, Fut> MiddlewareFunc for Func
56where
57    Func: FnOnce(Request, Next) -> Fut,
58    Func: Clone + Send + Sync + 'static,
59    Fut: Future<Output = Res> + Send,
60    Res: IntoResponse,
61{
62    async fn call(self, request: Request, next: Next) -> Response {
63        self(request, next).await.into_response()
64    }
65}