diff --git a/src/http/handler.rs b/src/http/handler.rs index 3c33647..d76aaf8 100644 --- a/src/http/handler.rs +++ b/src/http/handler.rs @@ -53,8 +53,29 @@ fn request_handler(client: &mut super::HttpStream) { [endpoint] => match usimp::is_valid_endpoint(endpoint) { true => match req.method { Method::POST => { - // TODO - res.status(200) + let mut buf = [0; 8192]; + + let length = req.find_header("Content-Length"); + let length: usize = length.unwrap().parse().unwrap(); + + client.stream.read_exact(&mut buf[..length]); + + // TODO decompress + let input = + json::parse(std::str::from_utf8(&buf[..length]).unwrap()).unwrap(); + let output = usimp::endpoint(endpoint, input); + + // TODO compress + let buf = output.to_string() + "\n"; + let length = buf.as_bytes().len(); + res.add_header("Content-Length", length.to_string().as_str()); + res.add_header("Content-Type", "application/json; charset=utf-8"); + + res.status(200); + res.send(&mut client.stream); + client.stream.write_all(buf.as_bytes()); + + return; } _ => { res.status(405); diff --git a/src/http/mod.rs b/src/http/mod.rs index f81a18f..acdf06b 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -160,6 +160,21 @@ pub struct Response { header_fields: Vec, } +impl Request { + pub fn find_header(&self, header_name: &str) -> Option { + for field in &self.header_fields { + if field + .name + .to_lowercase() + .eq(header_name.to_ascii_lowercase().as_str()) + { + return Some(field.value.clone()); + } + } + return None; + } +} + impl Response { pub fn new() -> Response { Response { diff --git a/src/usimp/mod.rs b/src/usimp/mod.rs index 72dc0e5..7cbc2f0 100644 --- a/src/usimp/mod.rs +++ b/src/usimp/mod.rs @@ -1,7 +1,25 @@ use json; +static ENDPOINTS: [(&str, fn(json::JsonValue) -> json::JsonValue); 1] = [("echo", echo)]; + pub fn is_valid_endpoint(endpoint: &str) -> bool { + for (name, _func) in &ENDPOINTS { + if endpoint.eq(*name) { + return true; + } + } false } -pub fn endpoint(endpoint: &str, input: json::object::Object) {} +pub fn endpoint(endpoint: &str, input: json::JsonValue) -> json::JsonValue { + for (name, func) in &ENDPOINTS { + if endpoint.eq(*name) { + return func(input); + } + } + panic!("invalid endpoint, check with is_valid_endpoint") +} + +pub fn echo(input: json::JsonValue) -> json::JsonValue { + input +} diff --git a/src/websocket/mod.rs b/src/websocket/mod.rs index 7a56c89..0fd0172 100644 --- a/src/websocket/mod.rs +++ b/src/websocket/mod.rs @@ -5,7 +5,6 @@ pub fn connection_handler(client: &mut http::HttpStream, req: &http::Request) { let mut res = http::Response::new(); if let http::Method::GET = req.method { - res.status(501); } else { res.status(405); res.add_header("Allow", "GET"); @@ -13,5 +12,7 @@ pub fn connection_handler(client: &mut http::HttpStream, req: &http::Request) { return; } + // TODO implement websocket + res.status(501); res.send(&mut client.stream); }