81 lines
2.2 KiB
Rust
81 lines
2.2 KiB
Rust
use axum::{
|
|
routing::get,
|
|
Router,
|
|
Json,
|
|
};
|
|
use std::sync::Arc;
|
|
use tower_http::cors::{CorsLayer, Any};
|
|
use tracing_subscriber;
|
|
|
|
mod blockchain;
|
|
mod auth;
|
|
mod middleware;
|
|
mod error;
|
|
mod config;
|
|
mod models;
|
|
mod wallet;
|
|
mod exchange;
|
|
|
|
use blockchain::NacClient;
|
|
use config::Config;
|
|
use models::HealthResponse;
|
|
|
|
#[tokio::main]
|
|
async fn main() {
|
|
// 初始化日志
|
|
tracing_subscriber::fmt::init();
|
|
|
|
// 加载配置
|
|
let config = Config::from_file("config.toml")
|
|
.unwrap_or_else(|_| {
|
|
tracing::warn!("无法加载配置文件,使用默认配置");
|
|
let default_config = Config::default();
|
|
// 保存默认配置到文件
|
|
let _ = default_config.save_to_file("config.toml");
|
|
default_config
|
|
});
|
|
|
|
// 创建区块链客户端
|
|
let nac_client = Arc::new(NacClient::new(config.blockchain.rpc_url.clone()));
|
|
|
|
// 创建路由
|
|
let app = Router::new()
|
|
.route("/", get(root))
|
|
.route("/health", get(health_check))
|
|
// 钱包API
|
|
.nest("/api/wallet", wallet::routes(nac_client.clone()))
|
|
// 交易所API
|
|
.nest("/api/exchange", exchange::routes(nac_client.clone()))
|
|
// 中间件
|
|
.layer(axum::middleware::from_fn(middleware::logging_middleware))
|
|
.layer(axum::middleware::from_fn(middleware::request_id_middleware))
|
|
// CORS配置
|
|
.layer(
|
|
CorsLayer::new()
|
|
.allow_origin(Any)
|
|
.allow_methods(Any)
|
|
.allow_headers(Any)
|
|
);
|
|
|
|
// 启动服务器
|
|
let addr = format!("{}:{}", config.server.host, config.server.port);
|
|
tracing::info!("🚀 NAC API服务器启动在 http://{}", addr);
|
|
tracing::info!("📡 区块链RPC: {}", config.blockchain.rpc_url);
|
|
|
|
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
|
|
axum::serve(listener, app).await.unwrap();
|
|
}
|
|
|
|
async fn root() -> &'static str {
|
|
"NAC API Server v1.0.0"
|
|
}
|
|
|
|
async fn health_check() -> Json<HealthResponse> {
|
|
Json(HealthResponse {
|
|
status: "ok".to_string(),
|
|
version: "1.0.0".to_string(),
|
|
block_height: 0, // TODO: 从区块链获取真实区块高度
|
|
timestamp: chrono::Utc::now().timestamp(),
|
|
})
|
|
}
|