use axum::{
extract::{Path, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::{get, post},
Json, Router,
};
use std::sync::Arc;
use crate::GatewayState;
async fn proxy_get(state: &GatewayState, path: &str) -> Response {
let url = format!("{}{}", state.sidecar_url, path);
match ureq::get(&url).call() {
Ok(res) => {
let status = StatusCode::from_u16(res.status()).unwrap_or(StatusCode::OK);
let body: serde_json::Value = res.into_json().unwrap_or(serde_json::Value::Null);
(status, Json(body)).into_response()
}
Err(ureq::Error::Status(code, res)) => {
let status = StatusCode::from_u16(code).unwrap_or(StatusCode::BAD_REQUEST);
let body: serde_json::Value = res.into_json().unwrap_or(serde_json::Value::Null);
(status, Json(body)).into_response()
}
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"status": "error",
"message": format!("Failed to proxy GET {} to sidecar: {}", path, e),
})),
)
.into_response(),
}
}
async fn proxy_post(state: &GatewayState, path: &str, payload: &serde_json::Value) -> Response {
let url = format!("{}{}", state.sidecar_url, path);
match ureq::post(&url).send_json(payload) {
Ok(res) => {
let status = StatusCode::from_u16(res.status()).unwrap_or(StatusCode::OK);
let body: serde_json::Value = res.into_json().unwrap_or(serde_json::Value::Null);
(status, Json(body)).into_response()
}
Err(ureq::Error::Status(code, res)) => {
let status = StatusCode::from_u16(code).unwrap_or(StatusCode::BAD_REQUEST);
let body: serde_json::Value = res.into_json().unwrap_or(serde_json::Value::Null);
(status, Json(body)).into_response()
}
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"status": "error",
"message": format!("Failed to proxy POST {} to sidecar: {}", path, e),
})),
)
.into_response(),
}
}
async fn get_profile(
State(state): State<Arc<GatewayState>>,
Path(agent_id): Path<String>,
) -> Response {
let path = format!("/api/v1/profile/{}", agent_id);
proxy_get(&state, &path).await
}
async fn create_profile(
State(state): State<Arc<GatewayState>>,
Json(payload): Json<serde_json::Value>,
) -> Response {
proxy_post(&state, "/api/v1/profile", &payload).await
}
pub fn router() -> Router<Arc<GatewayState>> {
Router::new()
.route("/api/v1/profile/:agent_id", get(get_profile))
.route("/api/v1/profile", post(create_profile))
}