]>
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 | // ANCHOR: here | |
6 | use std::thread; | |
7 | use std::time::Duration; | |
8 | // --snip-- | |
9 | // ANCHOR_END: here | |
10 | ||
11 | fn 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 | ||
22 | fn 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 |