From f95d7fa0bfdb818fbc8aada5cc4ab3c2aeea876c Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Fri, 3 Sep 2021 10:06:07 +0200 Subject: [PATCH 1/1] simple-http: Parse path from request --- simple-http/{hello.html => index.html} | 0 simple-http/src/main.rs | 33 ++++++++++++++++++++++---- 2 files changed, 29 insertions(+), 4 deletions(-) rename simple-http/{hello.html => index.html} (100%) diff --git a/simple-http/hello.html b/simple-http/index.html similarity index 100% rename from simple-http/hello.html rename to simple-http/index.html diff --git a/simple-http/src/main.rs b/simple-http/src/main.rs index 3036fcc..3316864 100644 --- a/simple-http/src/main.rs +++ b/simple-http/src/main.rs @@ -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") }; -- 2.39.2