use crate::contracts::support::Responsable;
use crate::http::{BoxFuture, Next};
use crate::http::{Method, Middleware, Request, Response};
use matchit::Router as MatchitRouter;
use std::borrow::Cow;
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
use super::into_middleware::{IntoMiddleware, MiddlewareItem};
use super::pending_route::{PendingRouteRegistrar, RouteGroupRegistrar};
pub type HandlerFn = Arc<dyn Fn(Request) -> BoxFuture<'static, Response> + Send + Sync + 'static>;
#[derive(Clone)]
pub(crate) struct RouteEntry {
pub(crate) handler: HandlerFn,
pub(crate) pipeline: Arc<[Arc<dyn Middleware>]>,
#[allow(dead_code)]
pub(crate) name: Option<String>,
#[allow(dead_code)]
pub(crate) domain: Option<String>,
#[allow(dead_code)]
pub(crate) wheres: HashMap<String, String>,
}
#[derive(Clone)]
pub struct Router {
routes: HashMap<Method, MatchitRouter<RouteEntry>>,
groups: HashMap<String, Vec<Arc<dyn Middleware>>>,
aliases: HashMap<String, Arc<dyn Middleware>>,
pub(crate) group_prefix: Option<String>,
pub(crate) group_middleware: Vec<MiddlewareItem>,
pub(crate) group_domain: Option<String>,
fallback_handler: HandlerFn,
}
impl Default for Router {
fn default() -> Self {
Self::new()
}
}
impl Router {
pub fn new() -> Self {
Self {
routes: HashMap::new(),
groups: HashMap::new(),
aliases: HashMap::new(),
group_prefix: None,
group_middleware: Vec::new(),
group_domain: None,
fallback_handler: Arc::new(|_req| {
Box::pin(async { Response::not_found().text("404 Not Found") })
}),
}
}
pub(crate) fn install_middleware(
&mut self,
groups: HashMap<String, Vec<Arc<dyn Middleware>>>,
aliases: HashMap<String, Arc<dyn Middleware>>,
) {
self.groups = groups;
self.aliases = aliases;
}
pub(crate) fn combine_prefix(&self, path: &str) -> String {
let clean_path = path.trim_start_matches('/');
match &self.group_prefix {
Some(prefix) => {
let trimmed = prefix.trim_matches('/');
if trimmed.is_empty() {
if clean_path.is_empty() {
"/".to_string()
} else {
format!("/{}", clean_path)
}
} else if clean_path.is_empty() {
format!("/{}", trimmed)
} else {
format!("/{}/{}", trimmed, clean_path)
}
}
None => {
if clean_path.is_empty() {
"/".to_string()
} else {
format!("/{}", clean_path)
}
}
}
}
pub(crate) fn insert_route(&mut self, method: Method, path: &str, entry: RouteEntry) {
let method_router = self.routes.entry(method).or_default();
method_router.insert(path, entry).unwrap();
}
pub(crate) fn compile_route_pipeline(
&self,
local_items: &[MiddlewareItem],
excluded_aliases: &[String],
) -> Arc<[Arc<dyn Middleware>]> {
let mut layers = Vec::new();
for item in &self.group_middleware {
self.resolve_middleware_item(item, &mut layers, excluded_aliases);
}
for item in local_items {
self.resolve_middleware_item(item, &mut layers, excluded_aliases);
}
layers.into()
}
fn resolve_middleware_item(
&self,
item: &MiddlewareItem,
layers: &mut Vec<Arc<dyn Middleware>>,
excluded_aliases: &[String],
) {
match item {
MiddlewareItem::Alias(name) => {
if excluded_aliases.contains(name) {
return;
}
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}]");
}
}
MiddlewareItem::Instance(instance) => {
layers.push(Arc::clone(instance));
}
}
}
pub fn group(&mut self, configure: impl FnOnce(&mut Self)) {
configure(self);
}
pub fn prefix(&mut self, prefix: impl Into<String>) -> RouteGroupRegistrar<'_> {
RouteGroupRegistrar::new(self).prefix(prefix)
}
pub fn middleware(&mut self, middleware: impl IntoMiddleware) -> RouteGroupRegistrar<'_> {
RouteGroupRegistrar::new(self).middleware(middleware)
}
pub fn domain(&mut self, domain: impl Into<String>) -> RouteGroupRegistrar<'_> {
RouteGroupRegistrar::new(self).domain(domain)
}
pub fn add_route<F, Fut, R>(
&mut self,
method: Method,
path: &str,
handler: F,
) -> PendingRouteRegistrar<'_>
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() })
});
PendingRouteRegistrar::new(self, vec![method], path, h)
}
pub fn get<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
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) -> PendingRouteRegistrar<'_>
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) -> PendingRouteRegistrar<'_>
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) -> PendingRouteRegistrar<'_>
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) -> PendingRouteRegistrar<'_>
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 any<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
let methods = vec![
Method::GET,
Method::POST,
Method::PUT,
Method::DELETE,
Method::PATCH,
];
let h: HandlerFn = Arc::new(move |req| {
let fut = handler(req);
Box::pin(async move { fut.await.to_response() })
});
PendingRouteRegistrar::new(self, methods, path, h)
}
pub fn r#match<F, Fut, R>(
&mut self,
methods: &[Method],
path: &str,
handler: F,
) -> PendingRouteRegistrar<'_>
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() })
});
PendingRouteRegistrar::new(self, methods.to_vec(), path, h)
}
pub fn dispatch(&self, mut req: Request) -> BoxFuture<'_, Response> {
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(Cow::Owned(key.to_string()), Cow::Owned(value.to_string()));
}
let handler = &matched.value.handler;
let pipeline = &matched.value.pipeline;
if pipeline.is_empty() {
return (handler)(req);
}
return Box::pin(async move {
let next = Next {
layers: pipeline,
index: 0,
handler,
};
next.run(req).await
});
}
}
(self.fallback_handler)(req)
}
}