]>
git.proxmox.com Git - rustc.git/blob - src/doc/book/listings/ch20-web-server/listing-20-20/src/main.rs
4 io
::{prelude::*, BufReader}
,
5 net
::{TcpListener, TcpStream}
,
11 let listener
= TcpListener
::bind("127.0.0.1:7878").unwrap();
12 let pool
= ThreadPool
::new(4);
14 for stream
in listener
.incoming() {
15 let stream
= stream
.unwrap();
18 handle_connection(stream
);
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();
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")
33 _
=> ("HTTP/1.1 404 NOT FOUND", "404.html"),
36 let contents
= fs
::read_to_string(filename
).unwrap();
37 let length
= contents
.len();
40 format
!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
42 stream
.write_all(response
.as_bytes()).unwrap();