chuanyue-service/server/src/lib.rs
2024-09-29 19:30:48 +08:00

55 lines
1.7 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use axum::{body::Body, extract::Request, routing::get, Router};
use library::{config, task};
use tasks::get_tasks;
use tower::ServiceBuilder;
use tower_http::trace::TraceLayer;
mod controller;
mod service;
mod tasks;
/// 启动服务
pub async fn serve() {
let addr = format!("0.0.0.0:{}", config!().server.port);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
tracing::info!("服务监听地址: {}", addr);
// 启动任务
task::start(get_tasks()).await;
// 启动应用服务
axum::serve(listener, init()).await.unwrap();
}
/// 初始化router包括router中间件和数据
fn init() -> Router {
let trace_layer = TraceLayer::new_for_http().make_span_with(|request: &Request<Body>| {
let req_id = match request
.headers()
.get("x-request-id")
.and_then(|value| value.to_str().ok())
{
Some(v) => v.to_string(),
None => String::from("unknown"),
};
tracing::error_span!("request_id", id = req_id)
});
let auth: Router = controller::init();
Router::new()
.route("/", get(|| async { "hello" }))
.nest("/gm/v1", auth)
.layer(
ServiceBuilder::new()
.layer(axum::middleware::from_fn(
library::middleware::req_ctx::authenticate_ctx,
))
.layer(axum::middleware::from_fn(
library::middleware::req_log::handle,
))
.layer(axum::middleware::from_fn(library::middleware::cors::handle))
.layer(axum::middleware::from_fn(
library::middleware::req_id::handle,
))
)
}