feat(HTTP): server basic responses + minor organization

This commit is contained in:
2024-11-21 23:56:14 +01:00
parent b302923c86
commit 7ea4e667ed
4 changed files with 79 additions and 14 deletions

View File

@@ -1,17 +1,7 @@
use std::io::prelude::*;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::net::{SocketAddr, TcpListener};
fn handle_petition(mut stream: TcpStream) -> std::io::Result<()> {
let mut buffer = [0; 1024];
let amount = stream.read(&mut buffer)?;
println!(
"Request: {} of {amount} bytes",
String::from_utf8_lossy(&buffer[..])
);
Ok(())
}
mod http;
fn main() {
let addr = SocketAddr::from(([127, 0, 0, 1], 80));
@@ -21,8 +11,25 @@ fn main() {
println!("Server up and running!");
for stream in listener.incoming() {
let _stream = stream.unwrap();
let mut _stream = stream.unwrap();
println!("Connection established!");
let _result = handle_petition(_stream);
let response = http::process_petition(&mut _stream);
// TODO: manage error case
match response {
Ok(data) => {
let _amount = _stream.write(data.data.as_bytes()).unwrap();
}
Err(e) => {
println!("Error: {:?}", e);
let _amount = _stream
.write(
"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n"
.as_bytes(),
)
.unwrap();
}
}
_stream.flush().unwrap();
}
}