feat: modularize codebase and add multi-route support with live reload

This commit is contained in:
danielvici123
2026-06-08 21:27:11 +02:00
parent 56d3b0f9e0
commit 922b7170a4
8 changed files with 320 additions and 0 deletions

54
src/handlers.rs Normal file
View File

@@ -0,0 +1,54 @@
use axum::{
extract::State,
http::{StatusCode, Uri},
response::IntoResponse,
Json,
};
use serde_json::json;
use std::fs;
use crate::state::SharedState;
use crate::config::Config;
pub async fn handler(
uri: Uri,
State(_state): State<SharedState>,
) -> impl IntoResponse {
let path = uri.path();
// 1. Reload config live on every request
let config = Config::load();
// 2. Find the route that matches the current path
let route = config.routes.iter().find(|r| r.path == path);
if let Some(route) = route {
match fs::read_to_string(&route.response_file) {
Ok(content) => {
match serde_json::from_str::<serde_json::Value>(&content) {
Ok(json) => {
let status = StatusCode::from_u16(route.status_code)
.unwrap_or(StatusCode::OK);
(status, Json(json)).into_response()
},
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Error parsing response JSON: {}", e),
).into_response(),
}
}
Err(e) => (
StatusCode::NOT_FOUND,
format!("Error reading response file: {}", e),
).into_response(),
}
} else {
fallback_handler().await.into_response()
}
}
pub async fn fallback_handler() -> impl IntoResponse {
(
StatusCode::NOT_FOUND,
Json(json!({ "error": "Not Found" })),
)
}