#2492·axum

通过 `ServiceBuilder` 使用 `RequestBodyLimitLayer` 时,在 v0.7 中无法编译

作者: markgomez创建于 2024年1月6日更新于 2026年9月14日

With ServiceBuilder, I was applying multiple middleware, the first of which was RequestBodyLimitLayer and everything compiled in v0.6 (when the B type parameter was still available). With Axum now having its own body type in v0.7, the following example no longer compiles:

rust
use axum::{
    extract::{Request, State},
    middleware::{self, Next},
    response::{Response, Result},
    routing::get,
    Router,
};
use tower::ServiceBuilder;
use tower_http::limit::RequestBodyLimitLayer;

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Hello, Axum!" }))
        .layer(
            ServiceBuilder::new()
                .layer(RequestBodyLimitLayer::new(1_048_576))
                .layer(middleware::from_fn_with_state("state", foo)),
        );

    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();

    axum::serve(listener, app).await.unwrap();
}

async fn foo(State(_state): State<&'static str>, req: Request, next: Next) -> Result<Response> {
    Ok(next.run(req).await)
}