3 use tokio::io::{ AsyncReadExt, AsyncWriteExt };
4 use tokio::net::{TcpListener, TcpStream};
8 let listener = TcpListener::bind("127.0.0.1:8181").await.unwrap();
11 let (stream, _) = listener.accept().await.unwrap();
12 tokio::spawn(async move { handle_connection(stream).await });
16 async fn handle_connection(mut stream: TcpStream) {
17 // Read the first 16 characters from the incoming stream
18 let mut buffer = [0; 16];
19 assert!(stream.read(&mut buffer).await.unwrap() >= 16);
20 // First 4 characters are used to detect HTTP method
21 let method_type = match str::from_utf8(&buffer[0..4]) {
23 Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
26 let contents = match method_type {
28 // todo: return real balance
29 format!("{{\"balance\": {}}}", 0.0)
32 // Take characters after 'POST /' until whitespace is detected.
33 let input: String = buffer[6..16]
35 .take_while(|x| **x != 32u8)
38 let balance_update = input.parse::<f32>().unwrap();
39 // todo: add balance update handling
40 format!("{{\"balance\": {}}}", balance_update)
43 panic!("Invalid HTTP method!")
47 let response = format!(
48 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
52 assert!(stream.write(response.as_bytes()).await.unwrap() > 0);
53 stream.flush().await.unwrap();