From 36cd153faba50df284dbc4c0db3af7682c79ab66 Mon Sep 17 00:00:00 2001 From: xfy Date: Tue, 1 Jul 2025 21:33:59 +0800 Subject: [PATCH] feat: add lua script route --- src/http/lua.rs | 40 +++++++++++++++++++++++++++++++--------- src/http/mod.rs | 13 ++++++++++++- 2 files changed, 43 insertions(+), 10 deletions(-) diff --git a/src/http/lua.rs b/src/http/lua.rs index f9b4584..9861ffb 100644 --- a/src/http/lua.rs +++ b/src/http/lua.rs @@ -1,27 +1,49 @@ +use anyhow::Context; +use axum::{ + body::Body, + extract::{Path, Request}, + response::IntoResponse, +}; +use axum_extra::extract::Host; +use http::Uri; +use tracing::error; + +use crate::{ + http::{HOSTS, error::RouteError, serve::resolve_parent_path}, + utils::parse_port_from_host, +}; + +use super::error::RouteResult; + pub async fn lua( req_uri: Uri, path: Option>, Host(host): Host, - mut req: Request, + req: Request, ) -> RouteResult { let req_path = req.uri().path(); - let path_query = req - .uri() - .path_and_query() - .map(|v| v.as_str()) - .unwrap_or(req_path); let scheme = req.uri().scheme_str().unwrap_or("http"); let port = parse_port_from_host(&host, scheme).ok_or(RouteError::BadRequest())?; - let route_map = &HOSTS.get(&port).ok_or(RouteError::BadRequest())?.route_map; + let route_map = &HOSTS + .get(&port) + .ok_or(RouteError::BadRequest()) + .with_context(|| { + format!("Hosts not found for port: {port}, host: {host}, scheme: {scheme}") + })? + .route_map; tracing::debug!("Route map entries: {:?}", route_map); let parent_path = resolve_parent_path(&req_uri, path.as_ref()); let route_config = route_map .get(&parent_path) - .ok_or(RouteError::RouteNotFound())?; + .ok_or(RouteError::RouteNotFound()) + .with_context(|| format!("route not found: {parent_path}"))?; let lua_script = route_config .lua_script .as_ref() - .ok_or(RouteError::InternalError())?; + .ok_or(RouteError::InternalError()) + .with_context(|| "lua script not found")?; + error!("Lua script: {lua_script}"); + Ok(()) } diff --git a/src/http/mod.rs b/src/http/mod.rs index 15de38f..3cc1dc7 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -20,6 +20,8 @@ pub mod error; pub mod serve; // handle reverse proxy pub mod reverse_proxy; +// handle lua script +pub mod lua; /// Host configuration /// use virtual host port as key @@ -45,8 +47,17 @@ pub async fn make_server(host: SettingHost) -> anyhow::Result<()> { // register routes for host_route in &host.route { // lua script - if let Some(lua_path) = &host_route.lua_script { + if host_route.lua_script.is_some() { // papare lua script + router = router.route(host_route.location.as_ref(), get(lua::lua)); + let route_path = format!("{}{{*path}}", host_route.location); + router = router.route(route_path.as_ref(), get(lua::lua)); + // save route path to map + { + host_to_save + .route_map + .insert(host_route.location.clone(), host_route.clone()); + } continue; }