new subdirmap macro, cleanups

This commit is contained in:
Dietmar Maurer 2018-11-01 15:41:08 +01:00
parent 763220cefa
commit bfcba4fd86
3 changed files with 34 additions and 10 deletions

View File

@ -3,6 +3,7 @@ use failure::*;
use crate::json_schema::*;
use serde_json::{Value};
#[derive(Debug)]
pub struct ApiMethod<'a> {
pub description: &'a str,
pub properties: &'a PropertyMap<'a>,
@ -12,6 +13,17 @@ pub struct ApiMethod<'a> {
pub type SubdirMap<'a> = crate::static_map::StaticMap<'a, &'a str, &'a MethodInfo<'a>>;
#[macro_export]
macro_rules! subdirmap {
($($name:ident => $e:expr),*) => {{
SubdirMap {
entries: &[
$( ( stringify!($name), $e), )*
]
}
}}
}
#[derive(Debug)]
pub struct MethodInfo<'a> {
pub get: Option<&'a ApiMethod<'a>>,
pub put: Option<&'a ApiMethod<'a>>,

View File

@ -131,4 +131,3 @@ pub static PVE_VMID: Jss = Integer!{
description => "The (unique) ID of the VM.",
minimum => Some(1)
};

View File

@ -74,7 +74,7 @@ fn test_api_handler(param: Value) -> Result<Value, Error> {
//}
let _force = param["force"].as_bool()
.ok_or_else(|| format_err!("meine fehlermeldung"))?;
.ok_or_else(|| format_err!("missing parameter 'force'"))?;
if let Some(_force) = param["force"].as_bool() {
}
@ -100,6 +100,10 @@ static TEST_API_METHOD: ApiMethod = ApiMethod {
};
static API3_TEST: MethodInfo = MethodInfo {
..METHOD_INFO_DEFAULTS
};
static API3_NODES: MethodInfo = MethodInfo {
get: Some(&TEST_API_METHOD),
..METHOD_INFO_DEFAULTS
@ -107,10 +111,9 @@ static API3_NODES: MethodInfo = MethodInfo {
static API_ROOT: MethodInfo = MethodInfo {
get: Some(&TEST_API_METHOD),
subdirs: Some(&SubdirMap {
entries: &[
("nodes", &API3_NODES),
]
subdirs: Some(&subdirmap!{
test => &API3_TEST,
nodes => &API3_NODES
}),
..METHOD_INFO_DEFAULTS
};
@ -166,7 +169,7 @@ fn handle_request(req: Request<Body>) -> Response<Body> {
&Method::DELETE => info.delete,
_ => None,
};
let _api_method = match api_method_opt {
let api_method = match api_method_opt {
Some(m) => m,
_ => http_error!(NOT_FOUND, format!("No such method '{} {}'\n", method, path)),
};
@ -174,11 +177,21 @@ fn handle_request(req: Request<Body>) -> Response<Body> {
// handle auth
// extract param
let _param = match query {
let param = match query {
Some(data) => parse_query(data),
None => json!({}),
};
match (api_method.handler)(param) {
Ok(res) => {
let json_str = res.to_string();
return Response::new(Body::from(json_str));
}
Err(err) => {
http_error!(NOT_FOUND, format!("Method returned error '{}'\n", err));
}
}
} else {
http_error!(NOT_FOUND, format!("No such path '{}'\n", path));
}