1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use futures::future::BoxFuture;
use std::sync::Arc;
use crate::{endpoint::DynEndpoint, Context, Response};
mod cookies;
mod default_headers;
mod logger;
pub use self::{cookies::CookiesMiddleware, default_headers::DefaultHeaders, logger::RootLogger};
pub trait Middleware<AppData>: 'static + Send + Sync {
fn handle<'a>(
&'a self,
cx: Context<AppData>,
next: Next<'a, AppData>,
) -> BoxFuture<'a, Response>;
}
impl<Data, F> Middleware<Data> for F
where
F: Send + Sync + 'static + for<'a> Fn(Context<Data>, Next<'a, Data>) -> BoxFuture<'a, Response>,
{
fn handle<'a>(&'a self, cx: Context<Data>, next: Next<'a, Data>) -> BoxFuture<'a, Response> {
(self)(cx, next)
}
}
pub struct Next<'a, AppData> {
pub(crate) endpoint: &'a DynEndpoint<AppData>,
pub(crate) next_middleware: &'a [Arc<dyn Middleware<AppData>>],
}
impl<'a, AppData: 'static> Next<'a, AppData> {
pub fn run(mut self, cx: Context<AppData>) -> BoxFuture<'a, Response> {
if let Some((current, next)) = self.next_middleware.split_first() {
self.next_middleware = next;
current.handle(cx, self)
} else {
(self.endpoint)(cx)
}
}
}