Rust axum 配置跨域和链路追踪日志

跨域

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!

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇