[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};
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"
}
}
+13 -9
View File
@@ -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<Body>) -> http::Result<Response<Body>> {
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<Body>) -> http::Result<Response<Body>> {
};
let paths: Vec<ReturnPath> = 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) }
}
}