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