X-Git-Url: https://piware.de/gitweb/?p=learn-rust.git;a=blobdiff_plain;f=simple-http%2Fsrc%2Fmain.rs;h=3036fcc669aaacac6b56ffe761f99166e7e006ab;hp=ca624762c2a1005335669710e0ceb54d254d2e3d;hb=852cbdeb56a1e3ad2ebc4686405bc0c7bd4cba81;hpb=02ebd7c33029bfbf8112cd8cb2649ca2ef2cd9d2;ds=sidebyside 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();