#[layer]Expand description
标记 Tower Layer
用于在路由处理函数或模块上应用 Tower Layer 中间件。
在函数上使用: 可以使用多个 #[layer] 属性,它们将从上到下声明,从内到外应用。
在模块上使用: 为模块内的所有路由自动添加指定的 layer。
用法:
ⓘ
use tower_http::timeout::TimeoutLayer;
use std::time::Duration;
// 单个 layer(函数级)
#[get("/users/{id}")]
#[layer(TimeoutLayer::new(Duration::from_secs(30)))]
async fn get_user(#[path] id: i32) -> impl IntoResponse {
// ...
}
// 多个 layer(函数级)
#[post("/users")]
#[layer(TimeoutLayer::new(Duration::from_secs(30)))]
#[layer(CompressionLayer::new())]
async fn create_user(#[body] user: User) -> impl IntoResponse {
// 调用链: CompressionLayer -> TimeoutLayer -> handler
}
// 模块级 layer
#[layer(AuthLayer::new())]
mod protected {
#[get("/data")]
async fn get_data() { } // 自动应用 AuthLayer
}