From f69328a8e9178ea4aeb9987e04958166eb0ed1bc Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Fri, 16 Sep 2022 11:17:26 +0200 Subject: [PATCH] tokio-tutorial-jbarszczewski: Add GET/POST parsing --- tokio-tutorial-jbarszczewski/src/main.rs | 34 ++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/tokio-tutorial-jbarszczewski/src/main.rs b/tokio-tutorial-jbarszczewski/src/main.rs index e1c7800..57af76b 100644 --- a/tokio-tutorial-jbarszczewski/src/main.rs +++ b/tokio-tutorial-jbarszczewski/src/main.rs @@ -1,4 +1,6 @@ -use tokio::io::AsyncWriteExt; +use std::str; + +use tokio::io::{ AsyncReadExt, AsyncWriteExt }; use tokio::net::{TcpListener, TcpStream}; #[tokio::main] @@ -12,7 +14,35 @@ async fn main() { } async fn handle_connection(mut stream: TcpStream) { - let contents = "{\"balance\": 0.00}"; + // Read the first 16 characters from the incoming stream + let mut buffer = [0; 16]; + assert!(stream.read(&mut buffer).await.unwrap() >= 16); + // First 4 characters are used to detect HTTP method + let method_type = match str::from_utf8(&buffer[0..4]) { + Ok(v) => v, + Err(e) => panic!("Invalid UTF-8 sequence: {}", e), + }; + + let contents = match method_type { + "GET " => { + // todo: return real balance + format!("{{\"balance\": {}}}", 0.0) + } + "POST" => { + // Take characters after 'POST /' until whitespace is detected. + let input: String = buffer[6..16] + .iter() + .take_while(|x| **x != 32u8) + .map(|x| *x as char) + .collect(); + let balance_update = input.parse::().unwrap(); + // todo: add balance update handling + format!("{{\"balance\": {}}}", balance_update) + } + _ => { + panic!("Invalid HTTP method!") + } + }; let response = format!( "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}", -- 2.39.5