]> piware.de Git - learn-rust.git/blob - async-http/src/main.rs
async-http: Move to async main and handler function
[learn-rust.git] / async-http / src / main.rs
1 use std::fs;
2 use std::io::prelude::*;
3 use std::net::{ TcpListener, TcpStream };
4 use std::time::Duration;
5
6 use async_std::task;
7
8 #[async_std::main]
9 async fn main() {
10     env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
11
12     // Listen for incoming TCP connections on localhost port 7878
13     let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
14
15     // Block forever, handling each request that arrives at this IP address
16     for stream in listener.incoming() {
17         let stream = stream.unwrap();
18         // not concurrent
19         handle_connection(stream).await;
20     }
21 }
22
23 async fn handle_connection(mut stream: TcpStream) {
24     // Read the first 1024 bytes of data from the stream
25     let mut buffer = [0; 1024];
26     assert!(stream.read(&mut buffer).unwrap() > 0);
27
28     // Respond with greetings or a 404,
29     // depending on the data in the request
30     let (status_line, filename) = if buffer.starts_with(b"GET / HTTP/1.1\r\n") {
31         ("HTTP/1.1 200 OK", "index.html")
32     } else if buffer.starts_with(b"GET /sleep HTTP/1.1\r\n") {
33         task::sleep(Duration::from_secs(5)).await;
34         ("HTTP/1.1 201 Sleep", "index.html")
35     } else {
36         ("HTTP/1.1 404 NOT FOUND", "404.html")
37     };
38     let contents = fs::read_to_string(filename).unwrap();
39     log::info!("GET {} {}", filename, status_line);
40
41     // Write response back to the stream,
42     // and flush the stream to ensure the response is sent back to the client
43     let response = format!("{status_line}\r\n\r\n{contents}");
44     stream.write_all(response.as_bytes()).unwrap();
45     stream.flush().unwrap();
46 }