From: Martin Pitt Date: Fri, 16 Sep 2022 08:53:18 +0000 (+0200) Subject: tokio-tutorial-jbarszczewski: Initial savings balance API X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=3999f76777dd4654553d944fb9e309150df8582f;p=learn-rust.git tokio-tutorial-jbarszczewski: Initial savings balance API --- diff --git a/tokio-tutorial-jbarszczewski/src/main.rs b/tokio-tutorial-jbarszczewski/src/main.rs index 6e69036..5d49be5 100644 --- a/tokio-tutorial-jbarszczewski/src/main.rs +++ b/tokio-tutorial-jbarszczewski/src/main.rs @@ -1,17 +1,24 @@ -use tokio::join; - -async fn guten_tag() { - println!("Guten Tag!"); -} +use tokio::io::AsyncWriteExt; +use tokio::net::{TcpListener, TcpStream}; #[tokio::main] async fn main() { - let task1 = tokio::spawn(async { - println!("Hello, world!"); - }); - let task2 = tokio::spawn(guten_tag()); + let listener = TcpListener::bind("127.0.0.1:8181").await.unwrap(); + + loop { + let (stream, _) = listener.accept().await.unwrap(); + handle_connection(stream).await; + } +} + +async fn handle_connection(mut stream: TcpStream) { + let contents = "{\"balance\": 0.00}"; - let (r1, r2) = join!(task1, task2); - r1.unwrap(); - r2.unwrap() + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}", + contents.len(), + contents + ); + assert!(stream.write(response.as_bytes()).await.unwrap() > 0); + stream.flush().await.unwrap(); }