跨域
1. 依赖
[dependencies]
tower-http = { version = "0.5.2", features = ["cors"] }
2. 配置
在router
的最后添加layer
(在路由配置的最后才生效)
// src/main.rs
use tower_http::{
cors::{Any, CorsLayer},
};
// 跨域配置
let origins = [
"http://localhost:5173".parse().unwrap(),
"https://blog.bg7zag.com".parse().unwrap(),
];
let cors = CorsLayer::new()
.allow_origin(origins)
.allow_methods(Any)
.allow_headers(Any);
let router = Router::new()
.route("/", get(|| async { ApiResponse::new("Hello World!", 0, "请求成功")}))
// 在路由最后添加cors
.layer(cors);
链路追踪日志
1. 依赖
[dependencies]
tower-http = { version = "0.5.2", features = ["trace"] }
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
2. 配置
// src/main.rs
use tower_http::{
trace::{self, TraceLayer},
};
use tracing::Level;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_target(false)
.compact()
.init();
// --snip--
let trace_layer = TraceLayer::new_for_http()
.make_span_with(trace::DefaultMakeSpan::new().level(Level::INFO))
.on_request(trace::DefaultOnRequest::new().level(Level::INFO))
.on_response(trace::DefaultOnResponse::new().level(Level::INFO));
let router = Router::new()
.route("/", get(|| async { ApiResponse::new("Hello World!", 0, "请求成功")}))
.layer(trace_layer);
// --snip--
}
Done!