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();
16 handle_connection(stream);
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();
25 let get = b"GET / HTTP/1.1\r\n";
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")
32 ("HTTP/1.1 404 NOT FOUND", "404.html")
34 let contents = fs::read_to_string(filename).unwrap();
35 log::info!("GET {} {}", filename, status_line);
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();