From 303e65e2a2e956923089a8ebbfa10a6496a2bf64 Mon Sep 17 00:00:00 2001 From: Azalea Gui Date: Fri, 17 Feb 2023 10:37:59 -0500 Subject: [PATCH] [O] Use trait instead of macros --- backend/src/macros.rs | 20 ++++++++++++-------- backend/src/main.rs | 14 ++++++++++---- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/backend/src/macros.rs b/backend/src/macros.rs index 3adf71f..e1f1bc4 100644 --- a/backend/src/macros.rs +++ b/backend/src/macros.rs @@ -1,11 +1,15 @@ -macro_rules! resp { - ($status:expr) => { - Response::builder().status($status) - }; +use hyper::{Body, http, Response, StatusCode}; + +pub trait StringExt { + fn resp(&self, status: u16) -> http::Result>; } -macro_rules! ok { - () => { - resp!(StatusCode::OK) - }; +impl StringExt for String { + fn resp(&self, status: u16) -> http::Result> { + Response::builder().status(StatusCode::from_u16(status).unwrap()).body(Body::from(self.to_owned())) + } } + +// fn main() { +// "a".resp() +// } diff --git a/backend/src/main.rs b/backend/src/main.rs index fced588..ada1f01 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -8,6 +8,8 @@ use std::os::unix::fs::MetadataExt; use hyper::{Body, http, Request, Response, Server, StatusCode}; use hyper::service::{make_service_fn, service_fn}; use serde::{Deserialize, Serialize}; +use path_clean::{clean}; +use macros::StringExt; #[tokio::main] async fn main() { @@ -38,13 +40,17 @@ struct ReturnPath { } async fn hello_world(_req: Request) -> http::Result> { - let path = _req.uri().path(); + let path = clean(_req.uri().path()); println!("{path}"); // List files in directory - let read_dir = match fs::read_dir(".") { + let read_dir = match fs::read_dir(path) { Ok(file) => {file} - Err(e) => { return resp!(500).body(format!("Error {e}").into()) } + Err(e) => { + let e_str = format!("Error {e}"); + if e.raw_os_error() == Some(2) { return e_str.resp(404) } + return e_str.resp(500) + } }; let paths: Vec = read_dir @@ -55,5 +61,5 @@ async fn hello_world(_req: Request) -> http::Result> { mtime: x.metadata().unwrap().mtime(), }).collect(); - ok!().body(serde_json::to_string(&paths).unwrap().into()) + serde_json::to_string(&paths).unwrap().resp(200) }