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