]> git.proxmox.com Git - rustc.git/blob - src/doc/book/listings/ch20-web-server/listing-20-23/src/main.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / src / doc / book / listings / ch20-web-server / listing-20-23 / src / main.rs
1 use hello::ThreadPool;
2 use std::{
3 fs,
4 io::{prelude::*, BufReader},
5 net::{TcpListener, TcpStream},
6 thread,
7 time::Duration,
8 };
9
10 fn main() {
11 let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
12 let pool = ThreadPool::new(4);
13
14 for stream in listener.incoming().take(2) {
15 let stream = stream.unwrap();
16
17 pool.execute(|| {
18 handle_connection(stream);
19 });
20 }
21
22 println!("Shutting down.");
23 }
24
25 fn handle_connection(mut stream: TcpStream) {
26 let buf_reader = BufReader::new(&mut stream);
27 let request_line = buf_reader.lines().next().unwrap().unwrap();
28
29 let (status_line, filename) = match &request_line[..] {
30 "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
31 "GET /sleep HTTP/1.1" => {
32 thread::sleep(Duration::from_secs(5));
33 ("HTTP/1.1 200 OK", "hello.html")
34 }
35 _ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
36 };
37
38 let contents = fs::read_to_string(filename).unwrap();
39 let length = contents.len();
40
41 let response =
42 format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
43
44 stream.write_all(response.as_bytes()).unwrap();
45 }