Browse Source

now serving 404's for everything non-root

jmelesky 7 years ago
parent
commit
76a4643eea
2 changed files with 22 additions and 4 deletions
  1. 8 0
      helloweb/404.html
  2. 14 4
      helloweb/src/main.rs

+ 8 - 0
helloweb/404.html

@@ -0,0 +1,8 @@
+<html>
+  <head>
+    <title>WFT?</title>
+  </head>
+  <body>
+    <h1>THERE IS NOTHING HERE. GO AWAY.</h1>
+  </body>
+</html>

+ 14 - 4
helloweb/src/main.rs

@@ -9,6 +9,7 @@ fn main() {
     let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
 
     for stream in listener.incoming() {
+        // "unwrap" means "just crash if there's an error"
         let stream = stream.unwrap();
 
         handle_connection(stream);
@@ -24,17 +25,26 @@ fn handle_connection(mut stream: TcpStream) {
 
     stream.read(&mut buffer).unwrap();
 
-    // hey, i'm reading a file!
-    let mut file = File::open("hello.html").unwrap();
+    let get = b"GET / HTTP/1.1\r\n";
+
+    let (status_line, filename) = if buffer.starts_with(get) {
+        ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
+    } else {
+        ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
+    };
+
+
+    let mut file = File::open(filename).unwrap();
 
     let mut contents = String::new();
     file.read_to_string(&mut contents).unwrap();
 
-    // slap that into a response
-    let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents);
+    let response = format!("{}{}", status_line, contents);
 
     stream.write(response.as_bytes()).unwrap();
     stream.flush().unwrap();
 
+
     println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
+
 }