]>
Commit | Line | Data |
---|---|---|
74b04a01 XL |
1 | use std::fs; |
2 | use std::io::prelude::*; | |
3 | use std::net::TcpListener; | |
4 | use std::net::TcpStream; | |
5 | use std::thread; | |
6 | use std::time::Duration; | |
7 | ||
8 | // ANCHOR: here | |
9 | fn 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 | // ANCHOR_END: here | |
22 | ||
23 | fn handle_connection(mut stream: TcpStream) { | |
f9f354fc | 24 | let mut buffer = [0; 1024]; |
74b04a01 XL |
25 | stream.read(&mut buffer).unwrap(); |
26 | ||
27 | let get = b"GET / HTTP/1.1\r\n"; | |
28 | let sleep = b"GET /sleep HTTP/1.1\r\n"; | |
29 | ||
30 | let (status_line, filename) = if buffer.starts_with(get) { | |
6a06907d | 31 | ("HTTP/1.1 200 OK", "hello.html") |
74b04a01 XL |
32 | } else if buffer.starts_with(sleep) { |
33 | thread::sleep(Duration::from_secs(5)); | |
6a06907d | 34 | ("HTTP/1.1 200 OK", "hello.html") |
74b04a01 | 35 | } else { |
6a06907d | 36 | ("HTTP/1.1 404 NOT FOUND", "404.html") |
74b04a01 XL |
37 | }; |
38 | ||
39 | let contents = fs::read_to_string(filename).unwrap(); | |
40 | ||
6a06907d XL |
41 | let response = format!( |
42 | "{}\r\nContent-Length: {}\r\n\r\n{}", | |
43 | status_line, | |
44 | contents.len(), | |
45 | contents | |
46 | ); | |
74b04a01 XL |
47 | |
48 | stream.write(response.as_bytes()).unwrap(); | |
49 | stream.flush().unwrap(); | |
50 | } |