From 455aa9677e598edbd190492a873d91b2bbe35aa8 Mon Sep 17 00:00:00 2001 From: Azalea Gui Date: Fri, 17 Feb 2023 10:09:26 -0500 Subject: [PATCH] [+] Macros, handle errors --- backend/src/macros.rs | 11 +++++++++++ backend/src/main.rs | 20 ++++++++++++++++---- 2 files changed, 27 insertions(+), 4 deletions(-) create mode 100644 backend/src/macros.rs diff --git a/backend/src/macros.rs b/backend/src/macros.rs new file mode 100644 index 0000000..3adf71f --- /dev/null +++ b/backend/src/macros.rs @@ -0,0 +1,11 @@ +macro_rules! resp { + ($status:expr) => { + Response::builder().status($status) + }; +} + +macro_rules! ok { + () => { + resp!(StatusCode::OK) + }; +} diff --git a/backend/src/main.rs b/backend/src/main.rs index 1eb3b63..fced588 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -1,8 +1,11 @@ +#[macro_use] +mod macros; + use std::convert::Infallible; use std::{env, fs}; use std::net::SocketAddr; use std::os::unix::fs::MetadataExt; -use hyper::{Body, Request, Response, Server}; +use hyper::{Body, http, Request, Response, Server, StatusCode}; use hyper::service::{make_service_fn, service_fn}; use serde::{Deserialize, Serialize}; @@ -34,8 +37,17 @@ struct ReturnPath { mtime: i64 } -async fn hello_world(_req: Request) -> Result, Infallible> { - let paths: Vec = fs::read_dir("./").unwrap() +async fn hello_world(_req: Request) -> http::Result> { + let path = _req.uri().path(); + println!("{path}"); + + // List files in directory + let read_dir = match fs::read_dir(".") { + Ok(file) => {file} + Err(e) => { return resp!(500).body(format!("Error {e}").into()) } + }; + + let paths: Vec = read_dir .map(|x| x.unwrap()) .map(|x| ReturnPath { name: x.file_name().to_str().unwrap().parse().unwrap(), @@ -43,5 +55,5 @@ async fn hello_world(_req: Request) -> Result, Infallible> mtime: x.metadata().unwrap().mtime(), }).collect(); - Ok(Response::new(serde_json::to_string(&paths).unwrap().into())) + ok!().body(serde_json::to_string(&paths).unwrap().into()) }