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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use crate::prelude::*;
use crate::regex_generator::generate_exact_match_regex;
use hyper::Request;
use regex::Regex;
use std::fmt::{self, Debug, Formatter};
use std::future::Future;
use std::pin::Pin;
type Handler<E> = Box<dyn FnMut(Request<hyper::Body>) -> HandlerReturn<E> + Send + Sync + 'static>;
type HandlerReturn<E> = Box<dyn Future<Output = Result<Request<hyper::Body>, E>> + Send + 'static>;
pub struct PreMiddleware<E> {
pub(crate) path: String,
regex: Regex,
pub(crate) handler: Option<Handler<E>>,
}
impl<E: std::error::Error + Send + Sync + Unpin + 'static> PreMiddleware<E> {
pub(crate) fn new_with_boxed_handler<P: Into<String>>(
path: P,
handler: Handler<E>,
) -> crate::Result<PreMiddleware<E>> {
let path = path.into();
let (re, _) = generate_exact_match_regex(path.as_str())
.context("Could not create an exact match regex for the pre middleware path")?;
Ok(PreMiddleware {
path,
regex: re,
handler: Some(handler),
})
}
pub fn new<P, H, R>(path: P, mut handler: H) -> crate::Result<PreMiddleware<E>>
where
P: Into<String>,
H: FnMut(Request<hyper::Body>) -> R + Send + Sync + 'static,
R: Future<Output = Result<Request<hyper::Body>, E>> + Send + 'static,
{
let handler: Handler<E> = Box::new(move |req: Request<hyper::Body>| Box::new(handler(req)));
PreMiddleware::new_with_boxed_handler(path, handler)
}
pub(crate) fn is_match(&self, target_path: &str) -> bool {
self.regex.is_match(target_path)
}
pub(crate) async fn process(&mut self, req: Request<hyper::Body>) -> crate::Result<Request<hyper::Body>> {
let handler = self
.handler
.as_mut()
.expect("A router can not be used after mounting into another router");
Pin::from(handler(req)).await.wrap()
}
}
impl<E> Debug for PreMiddleware<E> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{{ path: {:?}, regex: {:?} }}", self.path, self.regex)
}
}