1
1
use std:: io:: { Read , Write } ;
2
2
use std:: net:: { TcpListener , TcpStream } ;
3
- use std:: str:: FromStr ;
4
3
5
4
use nom:: branch:: alt;
6
5
use nom:: bytes:: streaming:: { tag_no_case as tag, take_until} ;
7
- use nom:: character:: complete:: one_of;
8
6
use nom:: IResult ;
9
7
use thiserror:: Error ;
10
8
@@ -32,6 +30,16 @@ pub enum ConnectionError {
32
30
ParsingError ( String ) , // TODO: improve parsing error
33
31
}
34
32
33
+ fn send_text_content ( stream : & mut TcpStream , txt : & str ) -> Result < ( ) , std:: io:: Error > {
34
+ stream. write ( "HTTP/1.1 200 OK\r \n " . as_bytes ( ) ) ?;
35
+ stream. write ( "Content-Type: text/plain\r \n " . as_bytes ( ) ) ?;
36
+ stream. write ( format ! ( "Content-Length: {}\r \n " , txt. len( ) ) . as_bytes ( ) ) ?;
37
+ stream. write ( "\r \n " . as_bytes ( ) ) ?;
38
+ stream. write ( txt. as_bytes ( ) ) ?;
39
+ stream. flush ( ) ?;
40
+ Ok ( ( ) )
41
+ }
42
+
35
43
fn handle_connection ( mut stream : TcpStream ) -> Result < ( ) , ConnectionError > {
36
44
let mut buffer = [ 0 ; 1024 ] ;
37
45
stream. read ( & mut buffer) ?; // read 1K bytes for now
@@ -43,6 +51,9 @@ fn handle_connection(mut stream: TcpStream) -> Result<(), ConnectionError> {
43
51
44
52
if req. path == "/" {
45
53
stream. write ( "HTTP/1.1 200 OK\r \n \r \n " . as_bytes ( ) ) . unwrap ( ) ;
54
+ } else if req. path . starts_with ( "/echo/" ) && req. path [ 6 ..] . find ( "/" ) . is_none ( ) {
55
+ let txt = & req. path [ 6 ..] ;
56
+ send_text_content ( & mut stream, txt) . unwrap ( ) ;
46
57
} else {
47
58
stream
48
59
. write ( "HTTP/1.1 404 Not Found\r \n \r \n " . as_bytes ( ) )
0 commit comments