From 44f7b9a00f72a35edc110c61e0222b690e782284 Mon Sep 17 00:00:00 2001 From: ErrorNoInternet Date: Wed, 12 Mar 2025 18:21:41 -0400 Subject: [PATCH] refactor(http): clean up routing --- src/http.rs | 45 +++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/src/http.rs b/src/http.rs index 3a40fa3..759510e 100644 --- a/src/http.rs +++ b/src/http.rs @@ -3,44 +3,45 @@ use crate::{ lua::{eval, exec, reload}, }; use http_body_util::{BodyExt, Empty, Full, combinators::BoxBody}; -use hyper::{Method, Request, Response, StatusCode, body::Bytes}; +use hyper::{ + Error, Method, Request, Response, StatusCode, + body::{Bytes, Incoming}, +}; pub async fn serve( - request: Request, + request: Request, state: State, -) -> Result>, hyper::Error> { - let path = request.uri().path().to_owned(); - - Ok(match (request.method(), path.as_str()) { - (&Method::POST, "/reload") => { - Response::new(full(format!("{:#?}", reload(&state.lua, None)))) - } - - (&Method::POST, "/eval" | "/exec") => { - let bytes = request.into_body().collect().await?.to_bytes(); - match std::str::from_utf8(&bytes) { - Ok(code) => Response::new(full(match path.as_str() { - "/eval" => format!("{:#?}", eval(&state.lua, code, None).await), - "/exec" => format!("{:#?}", exec(&state.lua, code, None).await), - _ => unreachable!(), - })), +) -> Result>, Error> { + macro_rules! handle_code { + ($handler:ident) => { + match std::str::from_utf8(&request.into_body().collect().await?.to_bytes()) { + Ok(code) => Response::new(full(format!( + "{:#?}", + $handler(&state.lua, code, None).await + ))), Err(error) => status_code_response( StatusCode::BAD_REQUEST, full(format!("invalid utf-8 data received: {error:?}")), ), } + }; + } + + Ok(match (request.method(), request.uri().path()) { + (&Method::POST, "/reload") => { + Response::new(full(format!("{:#?}", reload(&state.lua, None)))) } - + (&Method::POST, "/eval") => handle_code!(eval), + (&Method::POST, "/exec") => handle_code!(exec), (&Method::GET, "/ping") => Response::new(full("pong!")), - _ => status_code_response(StatusCode::NOT_FOUND, empty()), }) } fn status_code_response( status_code: StatusCode, - bytes: BoxBody, -) -> Response> { + bytes: BoxBody, +) -> Response> { let mut response = Response::new(bytes); *response.status_mut() = status_code; response