diff options
author | Adam Carpenter <53hornet@gmail.com> | 2019-03-26 15:05:10 -0400 |
---|---|---|
committer | Adam Carpenter <53hornet@gmail.com> | 2019-03-26 15:05:10 -0400 |
commit | 5718a0b54869b341bc74416bf82b716aa15d582c (patch) | |
tree | 0a1ab65ecc854733c15011f364524bde8379ae1b /hello_server/src/bin | |
parent | 29db8e4c4182877e5e723e26e2c5ae11e9383520 (diff) | |
download | learning-rust-5718a0b54869b341bc74416bf82b716aa15d582c.tar.xz learning-rust-5718a0b54869b341bc74416bf82b716aa15d582c.zip |
Finished web server project. Book done!
Diffstat (limited to 'hello_server/src/bin')
-rw-r--r-- | hello_server/src/bin/main.rs | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/hello_server/src/bin/main.rs b/hello_server/src/bin/main.rs new file mode 100644 index 0000000..522777a --- /dev/null +++ b/hello_server/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello_server::ThreadPool; +use std::thread; +use std::time::Duration; +use std::io::prelude::*; +use std::fs; +use std::net::TcpStream; +use std::net::TcpListener; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4).unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } + +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + 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\r\n\r\n", "hello.html") + } + else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } + else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + let response = format!("{}{}", status_line, contents); + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} |