use crate::contracts::Responsable;
use crate::http::{BoxFuture, Next}; use crate::http::{Method, Middleware, Request, Response};
use matchit::Router as MatchitRouter; use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
pub type HandlerFn = Arc<dyn Fn(Request) -> BoxFuture<'static, Response> + Send + Sync + 'static>;
#[derive(Clone)]
struct RouteEntry {
handler: HandlerFn,
pipeline: Arc<[Arc<dyn Middleware>]>,
}
pub struct Router {
routes: HashMap<Method, MatchitRouter<RouteEntry>>,
global: Vec<Arc<dyn Middleware>>,
groups: HashMap<String, Vec<Arc<dyn Middleware>>>,
aliases: HashMap<String, Arc<dyn Middleware>>,
stack: Vec<String>,
fallback_handler: HandlerFn,
fallback_pipeline: Arc<[Arc<dyn Middleware>]>,
}
impl Default for Router {
fn default() -> Self {
Self::new()
}
}
impl Router {
pub fn new() -> Self {
Self {
routes: HashMap::new(),
global: Vec::new(),
groups: HashMap::new(),
aliases: HashMap::new(),
stack: Vec::new(),
fallback_handler: Arc::new(|_req| {
Box::pin(async { Response::not_found().text("404 Not Found") })
}),
fallback_pipeline: Arc::new([]),
}
}
pub(crate) fn install_middleware(
&mut self,
global: Vec<Arc<dyn Middleware>>,
groups: HashMap<String, Vec<Arc<dyn Middleware>>>,
aliases: HashMap<String, Arc<dyn Middleware>>,
) {
self.global = global.clone();
self.groups = groups;
self.aliases = aliases;
self.fallback_pipeline = global.into();
}
pub fn group(&mut self, middleware: &[&str], configure: impl FnOnce(&mut Self)) {
let start = self.stack.len();
self.stack
.extend(middleware.iter().copied().map(str::to_string));
configure(self);
self.stack.truncate(start);
}
fn compile_pipeline(&self, local_names: &[String]) -> Arc<[Arc<dyn Middleware>]> {
let mut layers = self.global.clone();
for name in local_names {
if let Some(group) = self.groups.get(name) {
layers.extend(group.iter().cloned());
} else if let Some(alias) = self.aliases.get(name) {
layers.push(Arc::clone(alias));
} else {
panic!("Unknown middleware [{name}]");
}
}
layers.into() }
pub fn add_route<F, Fut, R>(&mut self, method: Method, path: &str, handler: F)
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
let h: HandlerFn = Arc::new(move |req| {
let fut = handler(req);
Box::pin(async move { fut.await.to_response() })
});
let pipeline = self.compile_pipeline(&self.stack);
let entry = RouteEntry {
handler: h,
pipeline,
};
let method_router = self.routes.entry(method).or_insert_with(MatchitRouter::new);
method_router.insert(path, entry).unwrap();
}
pub fn get<F, Fut, R>(&mut self, path: &str, handler: F)
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::GET, path, handler);
}
pub fn post<F, Fut, R>(&mut self, path: &str, handler: F)
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::POST, path, handler);
}
pub fn put<F, Fut, R>(&mut self, path: &str, handler: F)
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::PUT, path, handler);
}
pub fn delete<F, Fut, R>(&mut self, path: &str, handler: F)
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::DELETE, path, handler);
}
pub fn patch<F, Fut, R>(&mut self, path: &str, handler: F)
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::PATCH, path, handler);
}
pub fn dispatch(&self, mut req: Request) -> BoxFuture<'_, Response> {
let (handler, pipeline) = if let Some(method_router) = self.routes.get(&req.method) {
if let Ok(matched) = method_router.at(&req.path) {
for (key, value) in matched.params.iter() {
req.params.insert(key.to_string(), value.to_string());
}
(&matched.value.handler, &matched.value.pipeline)
} else {
(&self.fallback_handler, &self.fallback_pipeline)
}
} else {
(&self.fallback_handler, &self.fallback_pipeline)
};
if pipeline.is_empty() {
return (handler)(req);
}
Box::pin(async move {
let next = Next {
layers: pipeline,
index: 0,
handler,
};
next.run(req).await
})
}
}