]> git.proxmox.com Git - rustc.git/blame - src/doc/book/listings/ch20-web-server/listing-20-13/src/bin/main.rs
New upstream version 1.62.1+dfsg1
[rustc.git] / src / doc / book / listings / ch20-web-server / listing-20-13 / src / bin / main.rs
CommitLineData
74b04a01
XL
1use hello::ThreadPool;
2use std::fs;
3use std::io::prelude::*;
4use std::net::TcpListener;
5use std::net::TcpStream;
6use std::thread;
7use std::time::Duration;
8
9fn main() {
10 let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
11 let pool = ThreadPool::new(4);
12
13 for stream in listener.incoming() {
14 let stream = stream.unwrap();
15
16 pool.execute(|| {
17 handle_connection(stream);
18 });
19 }
20}
21
22fn handle_connection(mut stream: TcpStream) {
f9f354fc 23 let mut buffer = [0; 1024];
74b04a01
XL
24 stream.read(&mut buffer).unwrap();
25
26 let get = b"GET / HTTP/1.1\r\n";
27 let sleep = b"GET /sleep HTTP/1.1\r\n";
28
29 let (status_line, filename) = if buffer.starts_with(get) {
6a06907d 30 ("HTTP/1.1 200 OK", "hello.html")
74b04a01
XL
31 } else if buffer.starts_with(sleep) {
32 thread::sleep(Duration::from_secs(5));
6a06907d 33 ("HTTP/1.1 200 OK", "hello.html")
74b04a01 34 } else {
6a06907d 35 ("HTTP/1.1 404 NOT FOUND", "404.html")
74b04a01
XL
36 };
37
38 let contents = fs::read_to_string(filename).unwrap();
39
6a06907d
XL
40 let response = format!(
41 "{}\r\nContent-Length: {}\r\n\r\n{}",
42 status_line,
43 contents.len(),
44 contents
45 );
74b04a01
XL
46
47 stream.write(response.as_bytes()).unwrap();
48 stream.flush().unwrap();
49}