-
Notifications
You must be signed in to change notification settings - Fork 322
/
Copy pathmod.rs
46 lines (39 loc) · 1.4 KB
/
mod.rs
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
use futures::future::FutureObj;
use std::sync::Arc;
use crate::{endpoint::DynEndpoint, Context, Response};
mod default_headers;
mod logger;
pub use self::{default_headers::DefaultHeaders, logger::RootLogger};
/// Middleware that wraps around remaining middleware chain.
pub trait Middleware<AppData>: 'static + Send + Sync {
/// Asynchronously handle the request, and return a response.
fn handle<'a>(
&'a self,
cx: Context<AppData>,
next: Next<'a, AppData>,
) -> FutureObj<'a, Response>;
}
impl<Data, F> Middleware<Data> for F
where
F: Send + Sync + 'static + for<'a> Fn(Context<Data>, Next<'a, Data>) -> FutureObj<'a, Response>,
{
fn handle<'a>(&'a self, cx: Context<Data>, next: Next<'a, Data>) -> FutureObj<'a, Response> {
(self)(cx, next)
}
}
/// The remainder of a middleware chain, including the endpoint.
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> {
/// Asynchronously execute the remaining middleware chain.
pub fn run(mut self, cx: Context<AppData>) -> FutureObj<'a, Response> {
if let Some((current, next)) = self.next_middleware.split_first() {
self.next_middleware = next;
current.handle(cx, self)
} else {
(self.endpoint)(cx)
}
}
}