11use 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 ;
2+ use std:: {
3+ fs,
4+ io:: { prelude:: * , BufReader } ,
5+ net:: { TcpListener , TcpStream } ,
6+ thread,
7+ time:: Duration ,
8+ } ;
89
910fn main ( ) {
1011 let listener = TcpListener :: bind ( "127.0.0.1:7878" ) . unwrap ( ) ;
@@ -22,30 +23,23 @@ fn main() {
2223}
2324
2425fn 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) {
32- ( "HTTP/1.1 200 OK" , "hello.html" )
33- } else if buffer. starts_with ( sleep) {
34- thread:: sleep ( Duration :: from_secs ( 5 ) ) ;
35- ( "HTTP/1.1 200 OK" , "hello.html" )
36- } else {
37- ( "HTTP/1.1 404 NOT FOUND" , "404.html" )
26+ let buf_reader = BufReader :: new ( & mut stream) ;
27+ let request_line = buf_reader. lines ( ) . next ( ) . unwrap ( ) . unwrap ( ) ;
28+
29+ let ( status_line, filename) = match & request_line[ ..] {
30+ "GET / HTTP/1.1" => ( "HTTP/1.1 200 OK" , "hello.html" ) ,
31+ "GET /sleep HTTP/1.1" => {
32+ thread:: sleep ( Duration :: from_secs ( 5 ) ) ;
33+ ( "HTTP/1.1 200 OK" , "hello.html" )
34+ }
35+ _ => ( "HTTP/1.1 404 NOT FOUND" , "404.html" ) ,
3836 } ;
3937
4038 let contents = fs:: read_to_string ( filename) . unwrap ( ) ;
39+ let length = contents. len ( ) ;
4140
42- let response = format ! (
43- "{}\r \n Content-Length: {}\r \n \r \n {}" ,
44- status_line,
45- contents. len( ) ,
46- contents
47- ) ;
41+ let response =
42+ format ! ( "{status_line}\r \n Content-Length: {length}\r \n \r \n {contents}" ) ;
4843
4944 stream. write_all ( response. as_bytes ( ) ) . unwrap ( ) ;
50- stream. flush ( ) . unwrap ( ) ;
5145}
0 commit comments