improve router

This commit is contained in:
Dietmar Maurer 2018-11-15 13:28:15 +01:00
parent e63e99d646
commit 8a7005321b
3 changed files with 54 additions and 6 deletions

View File

@ -24,9 +24,24 @@ fn test_sync_api_handler(param: Value, _info: &ApiMethod) -> Result<Value, Error
Ok(json!(null))
}
fn test_subdir_api_handler(param: Value, _info: &ApiMethod) -> Result<Value, Error> {
println!("This is a subdir {}", param);
Ok(json!(null))
}
pub fn router() -> Router {
let route = Router::new()
let route3 = Router::new()
.get(ApiMethod {
handler: test_subdir_api_handler,
description: "Another Endpoint.",
parameters: parameter!{},
returns: Jss::Null,
});
let route2 = Router::new()
.get(ApiMethod {
handler: test_sync_api_handler,
description: "This is a simple test.",
@ -37,7 +52,15 @@ pub fn router() -> Router {
}
},
returns: Jss::Null,
})
.subdirs({
let mut map = HashMap::new();
map.insert("subdir3".into(), route3);
map
});
let route = Router::new()
.match_all(route2);
route
}

View File

@ -11,12 +11,18 @@ pub struct ApiMethod {
pub handler: fn(Value, &ApiMethod) -> Result<Value, Error>,
}
pub enum SubRoute {
None,
Hash(HashMap<String, Router>),
MatchAll { router: Box<Router>, param_name: String },
}
pub struct Router {
pub get: Option<ApiMethod>,
pub put: Option<ApiMethod>,
pub post: Option<ApiMethod>,
pub delete: Option<ApiMethod>,
pub subdirs: Option<HashMap<String, Router>>,
pub subroute: SubRoute,
}
impl Router {
@ -27,10 +33,20 @@ impl Router {
put: None,
post: None,
delete: None,
subdirs: None
subroute: SubRoute::None
}
}
pub fn subdirs(mut self, map: HashMap<String, Router>) -> Self {
self.subroute = SubRoute::Hash(map);
self
}
pub fn match_all(mut self, router: Router) -> Self {
self.subroute = SubRoute::MatchAll { router: Box::new(router), param_name: "test".into() };
self
}
pub fn get(mut self, m: ApiMethod) -> Self {
self.get = Some(m);
self
@ -42,10 +58,18 @@ impl Router {
let (dir, rest) = (components[0], &components[1..]);
if let Some(ref dirmap) = self.subdirs {
if let Some(ref info) = dirmap.get(dir) {
return info.find_route(rest);
match self.subroute {
SubRoute::None => {},
SubRoute::Hash(ref dirmap) => {
if let Some(ref router) = dirmap.get(dir) {
println!("FOUND SUBDIR {}", dir);
return router.find_route(rest);
}
}
SubRoute::MatchAll { ref router, ref param_name } => {
println!("URI PARAM {} = {}", param_name, dir); // fixme: store somewhere
return router.find_route(rest);
},
}
None

View File

@ -140,6 +140,7 @@ macro_rules! ApiString {
}}
}
#[macro_export]
macro_rules! parameter {
($($name:ident => $e:expr),*) => {{