improv: #5 handle the request and return a response (useful for tests)

This commit is contained in:
landrigun 2022-09-19 10:51:30 +01:00
parent 0a76efdc64
commit 617c084782
2 changed files with 18 additions and 9 deletions

View File

@ -122,7 +122,7 @@ impl HTTPStartLine {
HTTP_VERSION_REGEX.is_match(version)
}
fn is_valid(&self) -> bool {
pub fn is_valid(&self) -> bool {
return self.method != "" && self.target != "";
}
}
@ -234,7 +234,7 @@ impl HTTPRequest {
}
}
fn is_valid(&self) -> bool {
pub fn is_valid(&self) -> bool {
return self.start_line.is_valid();
}
}

View File

@ -25,14 +25,23 @@ async fn handle_connection(mut stream: TcpStream) {
let mut buffer: [u8; 1024] = [0; 1024];
let n = stream.read(&mut buffer).await.unwrap();
println!("buffer : {:?}", std::str::from_utf8(&buffer[0..n]));
let request_string = std::str::from_utf8(&buffer[0..n]).unwrap();
let request = handle_request(request_string);
let contents = "{\"balance\": 0.00}";
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
contents.len(),
contents
);
if request.is_valid() {
let contents = "{\"status\": \"ok\"}";
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
contents.len(),
contents
);
stream.write(response.as_bytes()).await.unwrap();
stream.flush().await.unwrap();
return;
}
let response = "HTTP/1.1 400 OK\r\n\r\n".to_string();
stream.write(response.as_bytes()).await.unwrap();
stream.flush().await.unwrap();
}