fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
+ let get_root = b"GET / HTTP/1.1\r\n";
stream.read(&mut buffer).unwrap();
println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
- let hello_contents = fs::read_to_string("hello.html").unwrap();
+ let (code, file) = if buffer.starts_with(get_root) {
+ ("200 OK", "hello.html")
+ } else {
+ ("404 NOT FOUND", "404.html")
+ };
+
+ let text = fs::read_to_string(file).unwrap();
let response = format!(
- "HTTP/1.1 200 OK\r\n\
+ "HTTP/1.1 {}\r\n\
Content-Type: text/html\r\n\
Content-Length: {}\r\n\r\n{}",
- hello_contents.len(),
- hello_contents);
+ code,
+ text.len(),
+ text);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();