From 20406b1d5808b77f50d0c8373d4d87bac5fa5495 Mon Sep 17 00:00:00 2001 From: gabe Date: Wed, 10 Aug 2022 13:10:32 -0500 Subject: [PATCH] added simple single threaded web server. --- the_book/http_server/404.html | 11 ++++++++ the_book/http_server/Cargo.toml | 8 ++++++ the_book/http_server/hello.html | 11 ++++++++ the_book/http_server/src/main.rs | 46 ++++++++++++++++++++++++++++++++ 4 files changed, 76 insertions(+) create mode 100644 the_book/http_server/404.html create mode 100644 the_book/http_server/Cargo.toml create mode 100644 the_book/http_server/hello.html create mode 100644 the_book/http_server/src/main.rs diff --git a/the_book/http_server/404.html b/the_book/http_server/404.html new file mode 100644 index 0000000..88d8e91 --- /dev/null +++ b/the_book/http_server/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/the_book/http_server/Cargo.toml b/the_book/http_server/Cargo.toml new file mode 100644 index 0000000..9bccf2c --- /dev/null +++ b/the_book/http_server/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "http_server" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/the_book/http_server/hello.html b/the_book/http_server/hello.html new file mode 100644 index 0000000..fe442d6 --- /dev/null +++ b/the_book/http_server/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/the_book/http_server/src/main.rs b/the_book/http_server/src/main.rs new file mode 100644 index 0000000..0419151 --- /dev/null +++ b/the_book/http_server/src/main.rs @@ -0,0 +1,46 @@ +use std::fs; +use std::time::Duration; +use std::thread; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + println!("Connection Established!"); + handle_connection(stream); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 1024]; + + stream.read(&mut buffer).unwrap(); + println!("Request: {}", String::from_utf8_lossy(&buffer[..])); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + let response = format!( + "{}\r\nContent-Length: {}\r\n\r\n{}", + status_line, + contents.len(), + contents, + ); + + stream.write_all(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +}