]>
Commit | Line | Data |
---|---|---|
74b04a01 | 1 | // ANCHOR: here |
923072b8 FG |
2 | use std::{ |
3 | fs, | |
4 | io::{prelude::*, BufReader}, | |
5 | net::{TcpListener, TcpStream}, | |
6 | thread, | |
7 | time::Duration, | |
8 | }; | |
74b04a01 XL |
9 | // --snip-- |
10 | // ANCHOR_END: here | |
11 | ||
12 | fn main() { | |
13 | let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); | |
14 | ||
15 | for stream in listener.incoming() { | |
16 | let stream = stream.unwrap(); | |
17 | ||
18 | handle_connection(stream); | |
19 | } | |
20 | } | |
21 | // ANCHOR: here | |
22 | ||
23 | fn handle_connection(mut stream: TcpStream) { | |
24 | // --snip-- | |
25 | ||
26 | // ANCHOR_END: here | |
923072b8 FG |
27 | let buf_reader = BufReader::new(&mut stream); |
28 | let request_line = buf_reader.lines().next().unwrap().unwrap(); | |
74b04a01 XL |
29 | |
30 | // ANCHOR: here | |
923072b8 FG |
31 | let (status_line, filename) = match &request_line[..] { |
32 | "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"), | |
33 | "GET /sleep HTTP/1.1" => { | |
34 | thread::sleep(Duration::from_secs(5)); | |
35 | ("HTTP/1.1 200 OK", "hello.html") | |
36 | } | |
37 | _ => ("HTTP/1.1 404 NOT FOUND", "404.html"), | |
74b04a01 XL |
38 | }; |
39 | ||
40 | // --snip-- | |
41 | // ANCHOR_END: here | |
42 | ||
43 | let contents = fs::read_to_string(filename).unwrap(); | |
923072b8 | 44 | let length = contents.len(); |
74b04a01 | 45 | |
923072b8 FG |
46 | let response = |
47 | format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); | |
74b04a01 | 48 | |
923072b8 | 49 | stream.write_all(response.as_bytes()).unwrap(); |
74b04a01 XL |
50 | // ANCHOR: here |
51 | } | |
52 | // ANCHOR_END: here |