From 47a1b71b5615603fec3d2af2a9d988851a30f984 Mon Sep 17 00:00:00 2001 From: Azalea Gui Date: Fri, 17 Feb 2023 12:09:38 -0500 Subject: [PATCH] [O] More error handling --- backend/src/macros.rs | 16 +++++++++++++--- backend/src/main.rs | 22 +++++++++++++--------- 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/backend/src/macros.rs b/backend/src/macros.rs index e1f1bc4..eb329d9 100644 --- a/backend/src/macros.rs +++ b/backend/src/macros.rs @@ -1,3 +1,4 @@ +use std::path::PathBuf; use hyper::{Body, http, Response, StatusCode}; pub trait StringExt { @@ -10,6 +11,15 @@ impl StringExt for String { } } -// fn main() { -// "a".resp() -// } +pub trait PathExt { + fn file_type(&self) -> &str; +} + +impl PathExt for PathBuf { + fn file_type(&self) -> &str { + if self.is_file() { return "file" } + if self.is_dir() { return "directory" } + if self.is_symlink() { return "link" } + "unknown" + } +} diff --git a/backend/src/main.rs b/backend/src/main.rs index 619d4fc..49b72a4 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -10,6 +10,7 @@ use hyper::service::{make_service_fn, service_fn}; use serde::{Deserialize, Serialize}; use path_clean::{clean}; use macros::StringExt; +use crate::macros::PathExt; #[tokio::main] async fn main() { @@ -41,11 +42,11 @@ struct ReturnPath { async fn hello_world(_req: Request) -> http::Result> { let path = format!(".{}", clean(_req.uri().path())); - println!("{path}"); + println!("Raw path: {} | Sanitized path: {path}", _req.uri().path()); // List files in directory let read_dir = match fs::read_dir(path) { - Ok(file) => {file} + Ok(file) => { file } Err(e) => { let e_str = format!("Error {e}"); if e.raw_os_error() == Some(2) { return e_str.resp(404) } @@ -54,12 +55,15 @@ async fn hello_world(_req: Request) -> http::Result> { }; let paths: Vec = read_dir - .map(|x| x.unwrap()) - .map(|x| ReturnPath { - name: x.file_name().to_str().unwrap().parse().unwrap(), - file_type: if x.path().is_file() { "file" } else { "directory" }.parse().unwrap(), - mtime: x.metadata().unwrap().mtime(), - }).collect(); + .filter_map(|x| x.ok()) + .filter_map(|x| Some(ReturnPath { + name: x.file_name().to_str()?.to_string(), + file_type: x.path().file_type().to_string(), + mtime: x.metadata().ok()?.mtime(), + })).collect(); - serde_json::to_string(&paths).unwrap().resp(200) + match serde_json::to_string(&paths) { + Ok(json) => { json.resp(200) } + Err(e) => { e.to_string().resp(500) } + } }