From 5ae5a42b2644afab404f99b01503d6dd7d6a01b1 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Fri, 16 Sep 2022 08:19:15 +0200 Subject: [PATCH] async-http: Move to async main and handler function This does not yet handle requests concurrently. Demonstrate with adding a /sleep path. --- async-http/Cargo.toml | 4 ++++ async-http/src/main.rs | 21 +++++++++++++-------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/async-http/Cargo.toml b/async-http/Cargo.toml index dfca1b5..92c94f5 100644 --- a/async-http/Cargo.toml +++ b/async-http/Cargo.toml @@ -8,3 +8,7 @@ edition = "2021" [dependencies] log = "0.4" env_logger = "0.9" + +[dependencies.async-std] +version = "1.6" +features = ["attributes"] diff --git a/async-http/src/main.rs b/async-http/src/main.rs index 95e7f07..c36be0a 100644 --- a/async-http/src/main.rs +++ b/async-http/src/main.rs @@ -1,9 +1,12 @@ use std::fs; use std::io::prelude::*; -use std::net::TcpListener; -use std::net::TcpStream; +use std::net::{ TcpListener, TcpStream }; +use std::time::Duration; -fn main() { +use async_std::task; + +#[async_std::main] +async fn main() { env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); // Listen for incoming TCP connections on localhost port 7878 @@ -12,21 +15,23 @@ fn main() { // Block forever, handling each request that arrives at this IP address for stream in listener.incoming() { let stream = stream.unwrap(); - handle_connection(stream); + // not concurrent + handle_connection(stream).await; } } -fn handle_connection(mut stream: TcpStream) { +async fn handle_connection(mut stream: TcpStream) { // Read the first 1024 bytes of data from the stream let mut buffer = [0; 1024]; assert!(stream.read(&mut buffer).unwrap() > 0); - let get = b"GET / HTTP/1.1\r\n"; - // Respond with greetings or a 404, // depending on the data in the request - let (status_line, filename) = if buffer.starts_with(get) { + let (status_line, filename) = if buffer.starts_with(b"GET / HTTP/1.1\r\n") { ("HTTP/1.1 200 OK", "index.html") + } else if buffer.starts_with(b"GET /sleep HTTP/1.1\r\n") { + task::sleep(Duration::from_secs(5)).await; + ("HTTP/1.1 201 Sleep", "index.html") } else { ("HTTP/1.1 404 NOT FOUND", "404.html") }; -- 2.39.5