1
- use std:: { fs, io:: { BufRead , BufReader , Write } , net:: { TcpListener , TcpStream } } ;
1
+ use std:: { fs, io:: { BufRead , BufReader , Write } , net:: { TcpListener , TcpStream } , thread , time :: Duration } ;
2
2
3
3
4
4
fn handle_connection ( mut stream : TcpStream ) {
5
5
let buf_reader = BufReader :: new ( & mut stream) ;
6
- let request_line = buf_reader. lines ( ) . next ( ) . unwrap ( ) . unwrap ( ) ;
6
+ let request_line: String = buf_reader. lines ( ) . next ( ) . unwrap ( ) . unwrap ( ) ;
7
+ eprint ! ( "Handling request: {request_line}" ) ;
7
8
8
9
// let http_request: Vec<_> = buf_reader
9
10
// .lines()
@@ -12,24 +13,29 @@ fn handle_connection(mut stream: TcpStream) {
12
13
// .collect();
13
14
// println!("Request: {:#?}", http_request);
14
15
15
-
16
- let ( status_line, filename) = if request_line == "GET / HTTP/1.1" {
17
- ( "HTTP/1.1 200 OK" , "hello.html" )
18
- } else {
19
- ( "HTTP/1.1 404 NOT FOUND" , "404.html" )
16
+ // must add & in front of request_line due to match unable to auto referencing and derefencing.
17
+ let ( status_line, filename) = match & request_line[ ..] {
18
+ "GET / HTTP/1.1" => ( "HTTP/1.1 200 OK" , "hello.html" ) ,
19
+ "GET /sleep HTTP/1.1" => {
20
+ thread:: sleep ( Duration :: from_secs ( 5 ) ) ;
21
+ ( "HTTP/1.1 200 OK" , "hello.html" ) } ,
22
+ _ => ( "HTTP/1.1 404 NOT FOUND" , "404.html" )
20
23
} ;
21
24
let contents = fs:: read_to_string ( filename) . unwrap ( ) ;
22
25
let length = contents. len ( ) ;
23
26
let response = format ! ( "{status_line}\r \n Content-Length: {length}\r \n \r \n {contents}" ) ;
24
- println ! ( "Handling request {request_line}" ) ;
25
27
stream. write_all ( response. as_bytes ( ) ) . unwrap ( ) ;
28
+ eprintln ! ( " Done." ) ;
26
29
}
30
+
27
31
fn main ( ) {
28
- println ! ( "{:#?}" , & [ 0 ; 3 ] ) ;
32
+ // [0; 3] is [0,0,0];
33
+ //println!("{:#?}", &[0; 3]);
34
+ println ! ( "Listening at TCP 127.0.0.1:7878." ) ;
29
35
let listener = TcpListener :: bind ( "127.0.0.1:7878" ) . unwrap ( ) ;
30
36
for stream in listener. incoming ( ) {
31
37
let stream = stream. unwrap ( ) ;
32
38
33
- handle_connection ( stream) ;
39
+ thread :: spawn ( || { handle_connection ( stream) ; } ) ;
34
40
}
35
41
}
0 commit comments