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