]> git.proxmox.com Git - rustc.git/blob - src/doc/book/listings/ch20-web-server/listing-20-22/src/main.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / src / doc / book / listings / ch20-web-server / listing-20-22 / 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() {
15 let stream = stream.unwrap();
16
17 pool.execute(|| {
18 handle_connection(stream);
19 });
20 }
21 }
22
23 fn handle_connection(mut stream: TcpStream) {
24 let buf_reader = BufReader::new(&mut stream);
25 let request_line = buf_reader.lines().next().unwrap().unwrap();
26
27 let (status_line, filename) = match &request_line[..] {
28 "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
29 "GET /sleep HTTP/1.1" => {
30 thread::sleep(Duration::from_secs(5));
31 ("HTTP/1.1 200 OK", "hello.html")
32 }
33 _ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
34 };
35
36 let contents = fs::read_to_string(filename).unwrap();
37 let length = contents.len();
38
39 let response =
40 format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
41
42 stream.write_all(response.as_bytes()).unwrap();
43 }