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