You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

74 lines
1.5 KiB

use axum::{
Json, Router,
extract::State,
http::StatusCode,
response::IntoResponse,
routing::{get, post},
};
use chrono::Utc;
use serde::Serialize;
use serde_json::Value;
use std::sync::Arc;
use crate::state::AppState;
// --- DTOs ---
#[derive(Debug, Serialize)]
pub struct EchoResponse {
pub data: Value,
pub timestamp: String,
}
#[derive(Debug, Serialize)]
pub struct VersionResponse {
pub name: String,
pub version: String,
}
#[derive(Debug, Serialize)]
pub struct ErrorResponse {
pub error: String,
}
impl IntoResponse for ErrorResponse {
fn into_response(self) -> axum::response::Response {
(StatusCode::INTERNAL_SERVER_ERROR, Json(self)).into_response()
}
}
impl<E: std::error::Error> From<E> for ErrorResponse {
fn from(err: E) -> Self {
Self {
error: err.to_string(),
}
}
}
// --- Handlers ---
pub async fn echo_handler(
State(_state): State<Arc<AppState>>,
Json(payload): Json<Value>,
) -> Result<Json<EchoResponse>, ErrorResponse> {
let response = EchoResponse {
data: payload,
timestamp: Utc::now().to_rfc3339(),
};
Ok(Json(response))
}
pub async fn version_handler(State(state): State<Arc<AppState>>) -> Json<VersionResponse> {
Json(VersionResponse {
name: state.name.clone(),
version: state.version.clone(),
})
}
// --- Router ---
pub fn routes() -> Router<Arc<AppState>> {
Router::new()
.route("/echo", post(echo_handler))
.route("/version", get(version_handler))
}