expression

Axum: bound buffered request bodies

A request size limit prevents supported buffering extractors from accepting arbitrarily large bodies. DefaultBodyLimit affects extractors that honor it, not every possible streamed read. Here the String extractor accepts a small body and rejects a larger one. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): 200 413 Common mistake: Assuming this extractor-specific limit automatically applies to every raw body stream.

Formal Syntax & Structure

rust syntaxrust
Router::layer(DefaultBodyLimit::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::{extract::DefaultBodyLimit, routing::post};    async fn count(body: String) -> String { body.len().to_string() }    let app = Router::new().route("/count", post(count)).layer(DefaultBodyLimit::max(4));    for body in ["abc", "12345"] {        let r = app.clone().oneshot(Request::builder().method("POST").uri("/count").body(Body::from(body)).unwrap()).await.unwrap();        println!("{}", r.status().as_u16());    }}
Rust Reference