2 use std::io::prelude::*;
3 use std::net::{ TcpListener, TcpStream };
4 use std::time::Duration;
10 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
12 // Listen for incoming TCP connections on localhost port 7878
13 let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
15 // Block forever, handling each request that arrives at this IP address
16 for stream in listener.incoming() {
17 let stream = stream.unwrap();
19 handle_connection(stream).await;
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);
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")
36 ("HTTP/1.1 404 NOT FOUND", "404.html")
38 let contents = fs::read_to_string(filename).unwrap();
39 log::info!("GET {} {}", filename, status_line);
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();