use crate::regex_generator::generate_exact_match_regex;
use crate::Error;
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,
pub(crate) regex: Regex,
pub(crate) handler: Option<Handler<E>>,
}
impl<E: Into<Box<dyn 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())?;
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) 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
.map_err(|e| Error::HandlePreMiddlewareRequest(e.into()))
}
}
impl<E> Debug for PreMiddleware<E> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{{ path: {:?}, regex: {:?} }}", self.path, self.regex)
}
}