]> piware.de Git - learn-rust.git/commitdiff
simple-http: Parse path from request
authorMartin Pitt <martin@piware.de>
Fri, 3 Sep 2021 08:06:07 +0000 (10:06 +0200)
committerMartin Pitt <martin@piware.de>
Fri, 3 Sep 2021 08:06:07 +0000 (10:06 +0200)
simple-http/hello.html [deleted file]
simple-http/index.html [new file with mode: 0644]
simple-http/src/main.rs

diff --git a/simple-http/hello.html b/simple-http/hello.html
deleted file mode 100644 (file)
index fe442d6..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-  <head>
-    <meta charset="utf-8">
-    <title>Hello!</title>
-  </head>
-  <body>
-    <h1>Hello!</h1>
-    <p>Hi from Rust</p>
-  </body>
-</html>
diff --git a/simple-http/index.html b/simple-http/index.html
new file mode 100644 (file)
index 0000000..fe442d6
--- /dev/null
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8">
+    <title>Hello!</title>
+  </head>
+  <body>
+    <h1>Hello!</h1>
+    <p>Hi from Rust</p>
+  </body>
+</html>
index 3036fcc669aaacac6b56ffe761f99166e7e006ab..3316864c12bc5095f0b68c021ae0ea469a21c9da 100644 (file)
@@ -3,16 +3,41 @@ use std::io::prelude::*;
 use std::net::TcpListener;
 use std::net::TcpStream;
 use std::fs;
+use std::str;
 
 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 (code, file) = if buffer.starts_with(get_root) {
-        ("200 OK", "hello.html")
+    let buffer = match str::from_utf8(&buffer[..]) {
+        Ok(s) => s,
+        Err(e) => {
+            eprintln!("Invalid non-UTF8 request: {}\n{}", e, String::from_utf8_lossy(&buffer[..]));
+            return;
+        }
+    };
+    println!("Request: {}", buffer);
+
+    let path;
+
+    // simple web server, just interested in first line
+    if let Some(line) = buffer.lines().next() {
+        let request: Vec<_> = line.split_whitespace().collect();
+        if request.len() != 3 || request[0] != "GET" || request[2] != "HTTP/1.1" {
+            stream.write(b"HTTP/1.1 501 NOT IMPLEMENTED\r\n").unwrap();
+            stream.flush().unwrap();
+            return;
+        }
+
+        path = request[1];
+    } else {
+        eprintln!("Ignoring empty request: {}", buffer);
+        return;
+    }
+
+    let (code, file) = if path == "/" || path == "/index.html" {
+        ("200 OK", "index.html")
     } else {
         ("404 NOT FOUND", "404.html")
     };