expression
Axum: early declared-length rejection
Tower HTTP can limit request bodies before extractors. A declared length over budget is rejected before the handler runs. For unknown lengths, the limit is enforced as the body is read; an unread body does not necessarily trigger an error. This example tests only the declared-length path. In-memory standalone Cargo example. Expected stdout (not executed): 200 413 Common mistake: Trusting a Content-Length header as the only size check.
Formal Syntax & Structure
rust syntaxrust
RequestBodyLimitLayer::new(max_bytes)Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use axum::routing::post; use tower_http::limit::RequestBodyLimitLayer; let app = Router::new().route("/", post(|| async { "handler ran" })).layer(RequestBodyLimitLayer::new(4)); for data in ["1234", "12345"] { let req = Request::builder().method("POST").header("content-length", data.len().to_string()).body(Body::from(data)).unwrap(); let r = app.clone().oneshot(req).await.unwrap(); println!("{}", r.status().as_u16()); }}