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