[O] More error handling

This commit is contained in:
Azalea Gui
2023-02-17 12:09:38 -05:00
parent 3f67edbc1f
commit 47a1b71b56
2 changed files with 26 additions and 12 deletions
+13 -3
View File
@@ -1,3 +1,4 @@
use std::path::PathBuf;
use hyper::{Body, http, Response, StatusCode}; use hyper::{Body, http, Response, StatusCode};
pub trait StringExt { pub trait StringExt {
@@ -10,6 +11,15 @@ impl StringExt for String {
} }
} }
// fn main() { pub trait PathExt {
// "a".resp() 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"
}
}
+13 -9
View File
@@ -10,6 +10,7 @@ use hyper::service::{make_service_fn, service_fn};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use path_clean::{clean}; use path_clean::{clean};
use macros::StringExt; use macros::StringExt;
use crate::macros::PathExt;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
@@ -41,11 +42,11 @@ struct ReturnPath {
async fn hello_world(_req: Request<Body>) -> http::Result<Response<Body>> { async fn hello_world(_req: Request<Body>) -> http::Result<Response<Body>> {
let path = format!(".{}", clean(_req.uri().path())); let path = format!(".{}", clean(_req.uri().path()));
println!("{path}"); println!("Raw path: {} | Sanitized path: {path}", _req.uri().path());
// List files in directory // List files in directory
let read_dir = match fs::read_dir(path) { let read_dir = match fs::read_dir(path) {
Ok(file) => {file} Ok(file) => { file }
Err(e) => { Err(e) => {
let e_str = format!("Error {e}"); let e_str = format!("Error {e}");
if e.raw_os_error() == Some(2) { return e_str.resp(404) } if e.raw_os_error() == Some(2) { return e_str.resp(404) }
@@ -54,12 +55,15 @@ async fn hello_world(_req: Request<Body>) -> http::Result<Response<Body>> {
}; };
let paths: Vec<ReturnPath> = read_dir let paths: Vec<ReturnPath> = read_dir
.map(|x| x.unwrap()) .filter_map(|x| x.ok())
.map(|x| ReturnPath { .filter_map(|x| Some(ReturnPath {
name: x.file_name().to_str().unwrap().parse().unwrap(), name: x.file_name().to_str()?.to_string(),
file_type: if x.path().is_file() { "file" } else { "directory" }.parse().unwrap(), file_type: x.path().file_type().to_string(),
mtime: x.metadata().unwrap().mtime(), mtime: x.metadata().ok()?.mtime(),
}).collect(); })).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) }
}
} }