Echo/reply working

This commit is contained in:
2021-05-16 17:28:14 +02:00
parent c3fe62275f
commit 124ff2ef94
4 changed files with 59 additions and 4 deletions

View File

@ -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);

View File

@ -160,6 +160,21 @@ pub struct Response {
header_fields: Vec<HeaderField>,
}
impl Request {
pub fn find_header(&self, header_name: &str) -> Option<String> {
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 {

View File

@ -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
}

View File

@ -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);
}