Add proper path parsing, add echo
Change-Id: Ic1475d9b49e80ec35a6e948b61c715ad639987c8
Reviewed-on: https://git.clicks.codes/c/Clicks/BYO/HttpServer/rust/+/249
Tested-by: Skyler Grey <minion@clicks.codes>
Reviewed-by: Samuel Shuert <coded@clicks.codes>
diff --git a/src/main.rs b/src/main.rs
index 1b23148..c24bdb2 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -8,19 +8,52 @@
Ok(mut _stream) => {
println!("accepted new connection");
- let mut buf: [u8; 6] = [0; 6];
+ let mut request: Vec<Vec<char>> = vec![vec![]];
+ let mut part: usize = 0;
- _stream.read_exact(&mut buf).unwrap();
+ loop {
+ let mut buf: [u8; 1] = [0; 1];
+ _stream.read_exact(&mut buf).unwrap();
- let status = if buf[5] == b' ' {
- "200 OK"
- } else {
- "404 Not Found"
- };
+ request[part].push(buf[0].into());
- let res_headers = "";
+ if buf[0] == b' ' {
+ part += 1;
+ request.push(vec![]);
+ }
- _stream.write(format!("HTTP/1.1 {status}\r\n{res_headers}\r\n").as_bytes()).unwrap();
+ if part == 2 {
+ break;
+ }
+ }
+
+ let unparsed_path = request[1].iter().collect::<String>();
+ let mut path = unparsed_path.split("/");
+
+ let response_status: &str;
+ let mut response_headers: Vec<String> = vec![];
+ let response_body: &str;
+
+ path.next().unwrap();
+
+ match path.next().unwrap() {
+ "" => {
+ response_status = "200 OK";
+ response_body = "";
+ },
+ "echo" => {
+ response_status = "200 OK";
+ response_body = path.next().unwrap();
+ response_headers.push("Content-Type: text/plain".to_owned());
+ response_headers.push(format!("Content-Length: {}", response_body.len()));
+ },
+ _ => {
+ response_status = "404 Not Found";
+ response_body = "";
+ }
+ }
+
+ _stream.write(format!("HTTP/1.1 {response_status}\r\n{}\r\n\r\n{response_body}\r\n", response_headers.join("\r\n")).as_bytes()).unwrap();
}
Err(e) => {
println!("error: {}", e);