use std::sync::Arc;
use regex::Regex;
use crate::controller::Controller;
use crate::http::*;
use crate::utils::ToRegex;
pub struct Builder {
routes: Vec<(Regex, Box<Controller>)>
}
impl Builder {
pub fn new() -> Self {
Builder {
routes: Vec::new()
}
}
pub fn add<C: 'static + Controller>(mut self, controller: C) -> Self {
self.routes.push((reg!(controller.base_path()), Box::new(controller)));
self
}
pub fn route<C: 'static + Controller, R: ToRegex>(mut self, route: R, controller: C) -> Self {
let mut cont_base_path = controller.base_path().to_string();
if cont_base_path.starts_with('^') {
cont_base_path.remove(0);
}
let mut route_str = route.as_str().to_string();
route_str.push_str(&cont_base_path);
self.routes.push((reg!(route_str), Box::new(controller)));
self
}
pub fn build(self) -> Router {
let Builder {
routes
} = self;
Router {
routes: Arc::new(routes),
}
}
}
pub struct Router {
routes: Arc<Vec<(Regex, Box<Controller>)>>
}
impl Router {
pub fn new() -> Self {
Router {
routes: Arc::new(Vec::new()),
}
}
pub fn dispatch(&self, req: &mut SyncRequest, res: &mut SyncResponse) {
let h: Option<(usize, &(Regex, Box<Controller>))> = self.routes.iter().enumerate().find(
|&(_, &(ref re, _))| {
req.current_path_match(re)
}
);
if let Some((_, &(_, ref controller))) = h {
controller.handle(req, res);
} else {
res.status(StatusCode::NOT_FOUND);
}
}
}
impl Clone for Router {
fn clone(&self) -> Self {
Router {
routes: self.routes.clone(),
}
}
}