expression
Axum: bound streamed body collection
Collect only when a response is known to fit a reasonable budget. A body can exceed its expected size even if it is streamed. This example intentionally exceeds a four-byte collection budget and checks the failure, without depending on the error text. In-memory standalone Cargo example. Expected stdout (not executed): over budget: true Common mistake: Using an unlimited collection budget for an untrusted body.
Formal Syntax & Structure
rust syntaxrust
to_bytes(body, limit).awaitWorking 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::body::Bytes; use futures_util::stream; use std::convert::Infallible; let body = Body::from_stream(stream::iter([Ok::<_, Infallible>(Bytes::from_static(b"abc")), Ok(Bytes::from_static(b"de"))])); println!("over budget: {}", to_bytes(body, 4).await.is_err());}