From bd1d20fd12eb6b661f3d76246ef09307e8114812 Mon Sep 17 00:00:00 2001 From: rrr-marble Date: Wed, 13 Oct 2021 22:34:31 +0300 Subject: [PATCH] add: conditional request handling --- src/main.rs | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 10c87a1..a913679 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,15 +15,35 @@ fn handle_connection(mut stream: TcpStream) { // make it 8k? // https://stackoverflow.com/questions/686217/maximum-on-http-header-values let mut buffer = [0; 1024]; - stream.read(&mut buffer).unwrap(); - let ip = stream.peer_addr().unwrap().ip().to_string(); - + let get = b"GET / HTTP/1.1\r\n"; + + let (status_line, contents) = if buffer.starts_with(get) { + ( + "HTTP/1.1 200 OK", + stream.peer_addr().unwrap().ip().to_string(), + ) + } else { + ( + "HTTP/1.1 404 NOT FOUND", + "\n404 Not Found\n\ + \n

404 Not Found

\n\ +
\n\n" + .to_string(), + ) + }; + + // add date header formatted to rfc2822? let response = format!( - "HTTP/1.1 200 OK\r\nContent-Lengh: {}\r\n\r\n{}", - ip.len(), - ip + "{}\r\n\ + Access-control-allow-origin: *\r\n\ + Content-type: text/plain; charset=utf-8\r\n\ + Content-Lengh: {}\r\n\r\n\ + {}", + status_line, + contents.len(), + contents ); stream.write(response.as_bytes()).unwrap();