expression
Axum: create a streamed response
A response body can pull data from a stream instead of assembling the entire payload first. The stream yields successful byte buffers or errors. Here two finite pieces form one text response; the test collects only up to 64 bytes. Stream items need not correspond to packets or client read boundaries. In-memory standalone Cargo example. Expected stdout (not executed): red blue Common mistake: Assuming every stream item arrives as a separate TCP packet.
Formal Syntax & Structure
rust syntaxrust
Body::from_stream(stream)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::get, body::Bytes}; use futures_util::stream; use std::convert::Infallible; let app = Router::new().route("/report", get(|| async { let chunks = [Ok::<_, Infallible>(Bytes::from_static(b"red\n")), Ok(Bytes::from_static(b"blue\n"))]; Body::from_stream(stream::iter(chunks)) })); let res = app.oneshot(Request::builder().uri("/report").body(Body::empty()).unwrap()).await.unwrap(); let data = to_bytes(res.into_body(), 64).await.unwrap(); print!("{}", std::str::from_utf8(&data).unwrap());}