use std::{fs, net::TcpStream};
use std::io::prelude::*;
use super::process::CliArgs;
#[derive(Debug)]
pub struct RequestObject {
pub method: String,
pub route: String,
}
impl RequestObject {
pub fn new(request: &String) -> Option<RequestObject> {
let allowed_methods = ["GET"];
let req_args: Vec<&str> = request.split(" ").collect();
let method = req_args[0];
let route = req_args[1];
assert!(allowed_methods.contains(&method), "Invalid request method");
assert!(route.starts_with("/"), "Invalid request route");
Some(RequestObject {
method: String::from(method),
route: String::from(route)
})
}
}
pub fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let str_buffer = String::from_utf8(buffer.clone().to_vec()).unwrap();
let request_obj = RequestObject::new(&str_buffer);
match &request_obj {
Some(req) => {
if req.method == "GET" {
let route = req.route.as_str();
let content: String;
match route {
value => {
let mut file_path = value;
if (!value.contains(".") && !value.contains(".html")) || value == "/index.html" {
file_path = "/index.html"
}
let file_content = fs::read_to_string(String::from(CliArgs::get().dir_path) + file_path);
match file_content {
Ok(data) => {
content = data.clone()
}
Err(_) => {
content = fs::read_to_string("assets/404.html").unwrap();
}
}
}
}
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
content.len(),
content,
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
}
None => {}
}
}