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