From 20d9d9d91c62efa140f8d99f1ade6c699e549fdc Mon Sep 17 00:00:00 2001 From: Snorre Ettrup Altschul Date: Wed, 26 Mar 2025 20:09:38 +0100 Subject: [PATCH] stuff --- src/main.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 632630b..c3089c2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,8 @@ use std::{ env::current_dir, ffi::OsStr, - fs::DirEntry, - io::{BufRead, BufReader, Read, Write}, + fs::{self, read, DirEntry}, + io::{self, BufRead, BufReader, Read, Write}, net::{TcpListener, TcpStream}, path::PathBuf, }; @@ -115,7 +115,7 @@ fn handle_connection(mut stream: TcpStream) { stream .write_all( { - match std::fs::read_dir("./public/posts/") { + match fs::read_dir("./public/posts/") { Ok(files) => { let mut entries = files .filter_map(|x| if x.is_ok() { Some(x.unwrap()) } else { None }) @@ -136,23 +136,23 @@ fn handle_connection(mut stream: TcpStream) { }) .collect::>(); entries.sort_by(|a, b| { - let mut a = if let Ok(a) = std::fs::File::open(a.path()) { + let mut a = if let Ok(a) = fs::File::open(a.path()) { a } else { let mut path = a.path().clone(); path.push("post.md"); - if let Ok(a) = std::fs::File::open(path) { + if let Ok(a) = fs::File::open(path) { a } else { return std::cmp::Ordering::Equal; } }; - let mut b = if let Ok(b) = std::fs::File::open(b.path()) { + let mut b = if let Ok(b) = fs::File::open(b.path()) { b } else { let mut path = b.path().clone(); path.push("post.md"); - if let Ok(b) = std::fs::File::open(path) { + if let Ok(b) = fs::File::open(path) { b } else { return std::cmp::Ordering::Equal; @@ -226,7 +226,7 @@ fn handle_connection(mut stream: TcpStream) { let mut response_content = vec![]; let response = match req.file() { - Some(path) => match std::fs::read(&path) { + Some(path) => match read(&path) { Ok(content) => { let len = &content.len(); response_content = content; @@ -237,7 +237,14 @@ fn handle_connection(mut stream: TcpStream) { get_mime_type(path.extension()) ) } - Err(e) => format!("HTTP/1.1 404{0}{0}{e}", CLRF), + Err(e) => + match e.kind() { + io::ErrorKind::NotFound => format!("HTTP/1.1 404\r\n\r\n{:?} not found", path.to_str()), + io::ErrorKind::PermissionDenied => format!("HTTP/1.1 403\r\n\r\n{:?} not readable", path.to_str()), + io::ErrorKind::FileTooLarge => format!("HTTP/1.1 413\r\n\r\n{:?} was too large", path.to_str()), + _ => format!("HTTP/1.1 500{0}{0}{e}", CLRF), + } + }, None => format!("HTTP/1.1 404{0}{0}", CLRF), };