refactor: clean up and restructure

This commit is contained in:
2025-02-16 01:10:48 -05:00
parent c4702a74f2
commit 645483c98f
15 changed files with 267 additions and 211 deletions

View File

@@ -5,24 +5,24 @@ use crate::{
use http_body_util::{BodyExt, Empty, Full, combinators::BoxBody};
use hyper::{Method, Request, Response, StatusCode, body::Bytes};
pub async fn handle(
pub async fn serve(
request: Request<hyper::body::Incoming>,
state: State,
) -> Result<Response<BoxBody<Bytes, hyper::Error>>, hyper::Error> {
let path = request.uri().path().to_owned();
match (request.method(), path.as_str()) {
(&Method::POST, "/reload") => Ok(match reload(&state.lua.lock()) {
Ok(match (request.method(), path.as_str()) {
(&Method::POST, "/reload") => match reload(&state.lua.lock()) {
Ok(()) => Response::new(empty()),
Err(error) => status_code_response(
StatusCode::INTERNAL_SERVER_ERROR,
Some(full(format!("{error:?}"))),
full(format!("{error:?}")),
),
}),
},
(&Method::POST, "/eval" | "/exec") => {
let bytes = request.into_body().collect().await?.to_bytes();
Ok(match std::str::from_utf8(&bytes) {
match std::str::from_utf8(&bytes) {
Ok(code) => {
let lua = state.lua.lock();
Response::new(full(match path.as_str() {
@@ -31,26 +31,24 @@ pub async fn handle(
_ => unreachable!(),
}))
}
Err(error) => {
return Ok(status_code_response(
StatusCode::BAD_REQUEST,
Some(full(format!("invalid utf-8 data received: {error:?}"))),
));
}
})
Err(error) => status_code_response(
StatusCode::BAD_REQUEST,
full(format!("invalid utf-8 data received: {error:?}")),
),
}
}
(&Method::GET, "/ping") => Ok(Response::new(full("pong!"))),
(&Method::GET, "/ping") => Response::new(full("pong!")),
_ => Ok(status_code_response(StatusCode::NOT_FOUND, None)),
}
_ => status_code_response(StatusCode::NOT_FOUND, empty()),
})
}
fn status_code_response(
status_code: StatusCode,
bytes: Option<BoxBody<Bytes, hyper::Error>>,
bytes: BoxBody<Bytes, hyper::Error>,
) -> Response<BoxBody<Bytes, hyper::Error>> {
let mut response = Response::new(bytes.unwrap_or(empty()));
let mut response = Response::new(bytes);
*response.status_mut() = status_code;
response
}