]> piware.de Git - learn-rust.git/commitdiff
simple-http: Check hardcoded root path, add 404 page
authorMartin Pitt <martin@piware.de>
Wed, 1 Sep 2021 10:17:54 +0000 (12:17 +0200)
committerMartin Pitt <martin@piware.de>
Wed, 1 Sep 2021 10:18:44 +0000 (12:18 +0200)
simple-http/404.html [new file with mode: 0644]
simple-http/src/main.rs

diff --git a/simple-http/404.html b/simple-http/404.html
new file mode 100644 (file)
index 0000000..d59a923
--- /dev/null
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8">
+    <title>Hello!</title>
+  </head>
+  <body>
+    <h1>Oops!</h1>
+    <p>I don't know about this resource.</p>
+  </body>
+</html>
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();