Handle errors for extract_first_line_of_request

This commit is contained in:
flyingscorpio@clevo 2023-01-08 23:36:49 +01:00
parent d02a4a9350
commit 1b29beec11

View file

@ -57,7 +57,6 @@ impl Ear {
/// Main event listener for the web server.
pub fn listen(&self) {
let listener = TcpListener::bind(format!("{}:{}", self.ip_addr, self.port)).unwrap();
println!("Listening on {}:{}", self.ip_addr, self.port);
for stream in listener.incoming() {
@ -65,8 +64,10 @@ impl Ear {
Ok(stream) => stream,
Err(_) => continue,
};
let req = self.extract_first_line_of_request(&stream);
let req = match extract_first_line_of_request(&stream) {
Some(req) => req,
None => continue,
};
let mut sender = Mouth::new(&stream);
println!("Received request: {}", &req);
@ -76,13 +77,15 @@ impl Ear {
};
}
}
}
/// Reads a stream in a buffer and extracts the first line.
fn extract_first_line_of_request(&self, mut stream: &TcpStream) -> String {
let buf_reader = BufReader::new(&mut stream);
let http_request = buf_reader.lines().next().unwrap().unwrap();
http_request
/// Reads a stream in a buffer and extracts the first line.
fn extract_first_line_of_request(mut stream: &TcpStream) -> Option<String> {
let buf_reader = BufReader::new(&mut stream);
let http_method = buf_reader.lines().next()?;
match http_method {
Ok(http_method) => Some(http_method),
Err(_) => None,
}
}