From 506c786cf554bef5757c6709a55bcb8d4a0d4bdf Mon Sep 17 00:00:00 2001 From: Dendy Faist Date: Fri, 13 Jan 2023 23:04:44 +0100 Subject: [PATCH] Add folder support --- src/main.rs | 46 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index ee713c2..6846dd6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ use std::convert::Infallible; +use std::path::Path; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Method, Request, Response, Server, StatusCode}; @@ -19,23 +20,54 @@ async fn hello_world(req: Request) -> Result, Infallible> { let mut response = Response::new(Body::empty()); match (req.method(), &path[..until]) { - (&Method::GET, "") => { - *response.body_mut() = Body::from("You shouldn't be reading this."); - } (&Method::GET, "blog") => { - *response.body_mut() = Body::from(file_to_md(path)); + *response.body_mut() = Body::from(path_access(path)); } (_, path) => { - *response.body_mut() = Body::from(format!("Path {path} not found.")); - *response.status_mut() = StatusCode::NOT_FOUND; + *response.body_mut() = Body::from(format!("Access to '{path}' isn't allowed.")); + *response.status_mut() = StatusCode::FORBIDDEN; } } Ok(response) } +fn path_access(path_str: &str) -> String { + let path = Path::new(path_str); + + if path.is_file() { + file_to_md(path_str) + } else if path.is_dir() { + list_directory(path_str) + } else { + format!("Path '{path_str}' doesn't exist!") + } +} + +fn list_directory(path_str: &str) -> String { + let folder = match Path::new(path_str).read_dir() { + Err(_) => return "Failed to read directory.".to_string(), + Ok(x) => x, + }; + + let mut string = String::new(); + + for entry in folder { + let entry = match entry { + Err(_) => return "Failed to read entry".to_string(), + Ok(x) => x, + }; + + if let Some(filename) = entry.file_name().to_str() { + string.push_str(format!(r#"{0}
"#, filename).as_str()); + } + } + + string +} + fn file_to_md(path: &str) -> String { - let file = std::fs::read_to_string(path).unwrap_or("File not found.".to_string()); + let file = std::fs::read_to_string(path).unwrap_or("Couldn't read file.".to_string()); //let mut options = Options::empty(); //options.insert(Options::ENABLE_STRIKETHROUGH);