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

9
docs/TODO.md Normal file
View File

@@ -0,0 +1,9 @@
# TODO
- [ ] Router
- [ ] HTTP code mapper
- [ ] JS / CSS data
- [ ] Media manager
- [ ] Log system
- [ ] File management
- [ ] Auto-cleanup
- [ ] Transversal utility

11
index.html Normal file
View File

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
HEY!
</body>
</html>

38
src/http.rs Normal file
View File

@@ -0,0 +1,38 @@
use std::fs;
use std::io::prelude::*;
use std::net::TcpStream;
pub struct ProcessedResponse {
pub data: String,
status: u8,
}
pub fn process_petition(stream: &mut TcpStream) -> std::io::Result<ProcessedResponse> {
let mut buffer = [0; 1024];
let _amount = stream.read(&mut buffer)?;
let petition = String::from_utf8_lossy(&buffer[..]);
let petition = petition.split("\n");
for line in petition {
println!("PART: {}", line)
}
let response_status = "200 OK";
let response_content = fs::read_to_string("./index.html").unwrap();
let response: ProcessedResponse = ProcessedResponse {
data: format!(
"HTTP/1.1 {}\r\nContent-Length: {}\r\n\r\n{}",
response_status,
response_content.len(),
response_content
),
status: 200,
};
Ok(response)
}

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();
}
}