use crate::request::Request;
use crate::response::Response;
use dashmap::DashMap;
pub trait Router: Send + Sync {
fn handle(&self, req: &Request) -> Response;
}
pub type Handler = Box<dyn Fn(&Request) -> Response + Send + Sync>;
pub struct DefaultRouter {
routes: DashMap<u32, Handler>,
}
impl DefaultRouter {
pub fn new() -> Self {
Self {
routes: DashMap::new(),
}
}
pub fn add_route<F>(&self, msg_id: u32, handler: F)
where
F: Fn(&Request) -> Response + Send + Sync + 'static,
{
self.routes.insert(msg_id, Box::new(handler));
}
}
impl Default for DefaultRouter {
fn default() -> Self {
Self::new()
}
}
impl Router for DefaultRouter {
fn handle(&self, req: &Request) -> Response {
match self.routes.get(&req.msg_id()) {
Some(handler) => handler(req),
None => Response::not_found(),
}
}
}