]> git.proxmox.com Git - rustc.git/blob - src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/main.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / src / doc / book / listings / ch20-web-server / no-listing-01-define-threadpool-struct / src / main.rs
1 // ANCHOR: here
2 use hello::ThreadPool;
3 // ANCHOR_END: here
4 use std::{
5 fs,
6 io::{prelude::*, BufReader},
7 net::{TcpListener, TcpStream},
8 thread,
9 time::Duration,
10 };
11
12 fn main() {
13 let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
14 let pool = ThreadPool::new(4);
15
16 for stream in listener.incoming() {
17 let stream = stream.unwrap();
18
19 pool.execute(|| {
20 handle_connection(stream);
21 });
22 }
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 }