]> piware.de Git - learn-rust.git/blobdiff - simple-http/src/main.rs
simple-http: Check hardcoded root path, add 404 page
[learn-rust.git] / simple-http / src / main.rs
index ca624762c2a1005335669710e0ceb54d254d2e3d..3036fcc669aaacac6b56ffe761f99166e7e006ab 100644 (file)
@@ -6,18 +6,26 @@ use std::fs;
 
 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();