PersonalWebApplication/Server/src/routes/web.rs

28 lines
896 B
Rust
Raw Normal View History

//! 前端React专用接口。挂 CORS仅放行前端开发源。
use axum::{Json, Router, extract::State, http::Method, routing::get};
use tower_http::cors::{AllowOrigin, CorsLayer};
use crate::{monitor::Stats, state::AppState};
pub fn router(state: AppState) -> Router {
// CORS只有浏览器会校验。放行前端开发源 + GET 方法即可。
let cors = CorsLayer::new()
.allow_origin(AllowOrigin::list([
"http://localhost:5173".parse().unwrap(),
"http://127.0.0.1:5173".parse().unwrap(),
]))
.allow_methods([Method::GET]);
Router::new()
.route("/api/web/stats", get(stats))
.layer(cors)
.with_state(state)
}
/// 返回最新系统状态快照。
async fn stats(State(state): State<AppState>) -> Json<Stats> {
let snapshot = state.snapshot.read().await.clone();
Json(snapshot)
}