Files
dhl/src/handlers.rs

55 lines
1.6 KiB
Rust

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" })),
)
}