1+ //! The HTTP Request
2+ //! Format : Method Request-URI HTTP-Version CRLF
3+ //! headers CRLF
4+ //! message-body
5+ //! The GET request : the client is asking for info
6+ //!
7+ //! Now onto the Writting a response
8+ //! HTTP-Version Status-Code Reason-Phrase CRLF
9+ //! headers CRLF
10+ //! message-body
11+ //! HTTP/1.1 200 OK\r\n\r\n -> Example of a response an "Ok" type one
112//! user imports
213use std:: {
14+ fs, //file system stuff
315 io:: { prelude:: * , BufReader } , // the std lib offers a module to listen to a TCP connection
416 net:: { TcpListener , TcpStream } ,
517} ;
@@ -19,11 +31,30 @@ fn main() {
1931}
2032
2133fn handle_connection ( mut stream : TcpStream ) {
22- let buf_reader = BufReader :: new ( & stream) ;
23- let http_request: Vec < _ > = buf_reader
24- . lines ( )
34+ let buf_reader = BufReader :: new ( & stream) ; //wraps a reference to
35+ //the stream
36+ let http_request: Vec < _ > = buf_reader // lines colected in a
37+ // vector
38+ . lines ( ) //method that returns an iterator of type
39+ //result<string, std::io:.Error>
2540 . map ( |result| result. unwrap ( ) )
2641 . take_while ( |line| !line. is_empty ( ) )
2742 . collect ( ) ;
2843 println ! ( "Request: {http_request:#?}" ) ;
44+
45+ let status_line = "HTTP/1.1 200 OK" ; //to say its "ok"
46+
47+ let contents = fs:: read_to_string ( "html/alo.html" ) . unwrap ( ) ;
48+ let length = contents. len ( ) ;
49+
50+ let response = format ! (
51+ "{}\r \n \
52+ Content-Length: {}\r \n \
53+ Content-Type: text/html\r \n \
54+ \r \n \
55+ {}",
56+ status_line, length, contents
57+ ) ;
58+
59+ stream. write_all ( response. as_bytes ( ) ) . unwrap ( ) ;
2960}
0 commit comments