From 852cbdeb56a1e3ad2ebc4686405bc0c7bd4cba81 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Wed, 1 Sep 2021 12:17:54 +0200 Subject: [PATCH] simple-http: Check hardcoded root path, add 404 page --- simple-http/404.html | 11 +++++++++++ simple-http/src/main.rs | 16 ++++++++++++---- 2 files changed, 23 insertions(+), 4 deletions(-) create mode 100644 simple-http/404.html diff --git a/simple-http/404.html b/simple-http/404.html new file mode 100644 index 0000000..d59a923 --- /dev/null +++ b/simple-http/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

I don't know about this resource.

+ + diff --git a/simple-http/src/main.rs b/simple-http/src/main.rs index ca62476..3036fcc 100644 --- a/simple-http/src/main.rs +++ b/simple-http/src/main.rs @@ -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(); -- 2.39.2