Custom stream IntoResponse wrapper

Learn how to wrap a stream and its headers in a small struct that implements IntoResponse so handlers can return it directly

A bare streamed body carries no headers. It has no content type, no file name, and no hint about what the bytes mean. Every handler that streams a download has to attach those headers by hand, next to the body, in a tuple. That works once. It gets repetitive the third time, and each copy is a chance to forget a header or mistype a value.

A wrapper struct solves that by putting the stream and its headers in one value. The struct holds the stream, the content type, and the file name. It implements IntoResponse, the trait that turns a value into an HTTP response. A handler then returns the struct directly, and the headers are attached the same way every time.

Where This Fits

The earlier pages in this cluster built streamed bodies and explained the wire format they travel in. This page is about the last piece of the shape: the headers that travel with the body. A stream on its own is anonymous bytes. A wrapper gives those bytes a name and a type, in a form the handler can return with one value.

Think of a bare body as a parcel with no label. The contents are fine, but nobody knows what is inside or who it is for. A wrapper is the same parcel with the label stuck on before it leaves. The label is written once, in one place, and every parcel of that kind leaves with the same label.

The Smallest Working Version

This example serves a file as a download. The struct holds the file stream, the file name, and the content type. The handler opens the file, builds the struct, and returns it.

Cargo.toml
[package]
name = "stream-wrapper-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tokio-util = { version = "0.7", features = ["io"] }
src/main.rs
use axum::{
    body::Body,
    http::{header, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use tokio_util::io::ReaderStream;

struct StreamDownload {
    stream: ReaderStream<tokio::fs::File>,
    filename: String,
    content_type: &'static str,
}

impl IntoResponse for StreamDownload {
    fn into_response(self) -> Response {
        let body = Body::from_stream(self.stream);
        let disposition = format!("attachment; filename=\"{}\"", self.filename);
        (
            [
                (header::CONTENT_TYPE, self.content_type),
                (header::CONTENT_DISPOSITION, disposition.as_str()),
            ],
            body,
        )
            .into_response()
    }
}

async fn download_handler() -> Result<StreamDownload, StatusCode> {
    let file = tokio::fs::File::open("report.bin")
        .await
        .map_err(|_| StatusCode::NOT_FOUND)?;
    Ok(StreamDownload {
        stream: ReaderStream::new(file),
        filename: "report.bin".to_string(),
        content_type: "application/octet-stream",
    })
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/download", get(download_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Ask for the headers:

curl -D - http://127.0.0.1:3000/download -o downloaded.bin

A live run against this exact code returned these headers, and the downloaded bytes matched the file on disk exactly:

HTTP/1.1 200 OK
content-type: application/octet-stream
content-disposition: attachment; filename="report.bin"
transfer-encoding: chunked
date: Sat, 14 Nov 2026 10:22:23 GMT

The handler is three lines long. Open the file, build the struct, return it. The content type, the file name, and the streaming itself all live inside the struct and its IntoResponse implementation. The handler does not repeat any of them.

Working Setup:

If the response shows content-disposition: attachment; filename="report.bin" and the downloaded file matches the original, the wrapper is working. The handler returned one struct, and the struct produced the headers and the streamed body together.

What Each Piece Does

The struct

struct StreamDownload {
    stream: ReaderStream<tokio::fs::File>,
    filename: String,
    content_type: &'static str,
}

A struct is a named bundle of values. This one bundles the three things a streamed download needs: the stream of bytes, the name the downloaded file should get, and the content type that says what the bytes are. The field types say exactly what each value is. The stream is a ReaderStream over a Tokio file, the same stream from the large-file page. The file name is an owned String, because it comes from the handler and the struct must own it. The content type is a &'static str, a string baked into the program, because content types are fixed words like application/octet-stream and never need to be built at runtime.

The struct owns its stream. Ownership matters here, because into_response consumes the struct. The stream moves out of the struct and into the body, and nothing is left behind. That is why the method takes self by value instead of by reference.

The IntoResponse implementation

impl IntoResponse for StreamDownload {
    fn into_response(self) -> Response {
        let body = Body::from_stream(self.stream);
        let disposition = format!("attachment; filename=\"{}\"", self.filename);
        (
            [
                (header::CONTENT_TYPE, self.content_type),
                (header::CONTENT_DISPOSITION, disposition.as_str()),
            ],
            body,
        )
            .into_response()
    }
}

IntoResponse is the trait Axum requires of handler return values. It has one method, into_response, which turns the value into a full Response. Implementing it for a struct is what lets a handler return that struct directly. Without the implementation, the compiler rejects the handler, because Axum would not know how to turn the struct into a response.

Inside the method, three things happen. First, the stream becomes a body with Body::from_stream, the same call from the earlier pages. Second, the disposition value is built with format!, which fills the file name into the attachment; filename="..." shape. The quotes around the name matter: a file name with a space in it, such as monthly report.csv, is only read correctly when it is quoted. Third, the headers and the body are paired as a tuple and turned into a response with .into_response(). Axum implements IntoResponse for tuples of headers and a body, so the tuple conversion does the final assembly.

content-disposition with attachment tells the client to download the body as a file instead of trying to display it. The file name after it tells the client what to call the saved file. Without this header, a browser receiving a CSV file might display it as a page. With it, the browser offers a download.

The handler

async fn download_handler() -> Result<StreamDownload, StatusCode> {
    let file = tokio::fs::File::open("report.bin")
        .await
        .map_err(|_| StatusCode::NOT_FOUND)?;
    Ok(StreamDownload {
        stream: ReaderStream::new(file),
        filename: "report.bin".to_string(),
        content_type: "application/octet-stream",
    })
}

The handler does the one thing that can fail, which is opening the file, and then builds the struct. The return type is Result<StreamDownload, StatusCode>, so a missing file becomes a 404 Not Found and a found file becomes the wrapper. Axum converts the Err side into an empty response with that status, and converts the Ok side through the IntoResponse implementation above. The handler never touches a header. That is the point of the wrapper: the handler decides what to send, and the struct decides how it is labelled.

The Wrapper Runs When the Handler Returns:

The into_response method runs after the handler returns, when Axum converts the return value into a response. The stream is built at that moment, and the first chunk is read after that, when the server starts writing the body. The wrapper adds no extra waiting. It only organises code that would otherwise sit in the handler.

Why a Wrapper Is Worth Writing

The first reason is reuse. A server that streams downloads from five routes would otherwise repeat the same header tuple five times. Each copy is a place where a content type can be mistyped or a disposition forgotten. The wrapper holds the pattern once, and every route uses it by constructing the same struct.

The second reason is that the handler stays readable. A handler that opens a file, builds a stream, builds a body, builds headers, and assembles a response is doing five jobs. A handler that opens a file and returns a struct is doing one job. The other four live in the struct, where they can be read and tested on their own.

The third reason is that the type documents the intent. A handler returning StreamDownload says what it is sending. A handler returning a tuple of headers and a body says only how it is built. The next person to read the code learns the purpose from the type name before reading a single line of the implementation.

The cost is a small amount of new code: one struct and one trait implementation. That cost pays for itself the second time the pattern is used, and it is worth paying even the first time when the headers are easy to get wrong.

A Generic Wrapper That Works With Any Stream

The struct above only works with a file stream. A server that also streams generated data, such as rows of a report built in memory, would need a second struct. A generic struct removes that limit. It takes the stream type as a parameter, so one wrapper serves every source.

src/main.rs
use axum::{
    body::{Body, Bytes},
    http::header,
    response::{IntoResponse, Response},
};
use futures_util::stream::{Stream, StreamExt};

pub struct StreamResponse<S> {
    pub stream: S,
    pub content_type: &'static str,
    pub filename: Option<String>,
}

impl<S, E> IntoResponse for StreamResponse<S>
where
    S: Stream<Item = Result<Bytes, E>> + Send + 'static,
    E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
    fn into_response(self) -> Response {
        let body = Body::from_stream(self.stream);
        let mut response = body.into_response();
        response.headers_mut().insert(
            header::CONTENT_TYPE,
            self.content_type.parse().unwrap(),
        );
        if let Some(name) = self.filename {
            let value = format!("attachment; filename=\"{}\"", name);
            response.headers_mut().insert(
                header::CONTENT_DISPOSITION,
                value.parse().unwrap(),
            );
        }
        response
    }
}

The generic version differs from the concrete one in four ways, and each one is worth naming.

S is the stream type, left open. Any stream works, as long as it meets the bounds in the where clause. The bounds are the same ones Body::from_stream requires: items of Result<Bytes, E>, a stream that is Send and 'static, and an error type that converts into a boxed error. Writing them on the implementation keeps the wrapper honest. A stream that cannot be turned into a body cannot be wrapped either, and the compiler says so at the wrapper instead of deep inside the handler.

filename is an Option<String>. Some means the response is a download with that name. None means the response is ordinary content with no disposition header, such as a live feed the client should display rather than save. One struct covers both cases, and the if let Some(name) in the implementation adds the header only when a name exists.

The headers are inserted into the response with headers_mut instead of a tuple. A tuple works when every header is always present. headers_mut works when a header is conditional, because the code can decide for each header whether to insert it. The parse().unwrap() converts a string into a header value. The values here come from fixed strings and a formatted file name, so parsing cannot fail in practice, but the unwrap still deserves a note, which the mistakes section below gives.

content_type is a &'static str again, and it is always set. A streamed body with no content type leaves the client guessing. The wrapper makes the content type mandatory by putting it in the struct, so no route can forget it.

This version needs one import the concrete version did not: Stream from futures_util::stream, which is the trait the bound refers to. StreamExt is imported alongside it for the stream helpers used by the examples below.

Using the Generic Wrapper for a Generated Report

A generated CSV report is a good second use. The rows do not come from a file. They are built one at a time, from data the handler already has. The wrapper does not care. It takes the stream and the headers, the same as before.

src/main.rs
use axum::{body::Body, body::Bytes, routing::get, Router};
use futures_util::stream;

async fn csv_handler() -> StreamResponse<impl stream::Stream<Item = Result<Bytes, std::io::Error>> + Send + 'static> {
    let rows = vec!["id,name\n", "1,ada\n", "2,grace\n"];
    let ticks = stream::iter(
        rows.into_iter()
            .map(|row| Ok::<Bytes, std::io::Error>(Bytes::from(row))),
    );
    StreamResponse {
        stream: ticks,
        content_type: "text/csv",
        filename: Some("people.csv".to_string()),
    }
}

The return type names the stream in place with impl Stream, which says "this handler returns a StreamResponse holding some stream of this shape, and the exact stream type is the compiler's business". The rows are fixed strings here, and each one becomes one chunk. In a real handler the rows would come from a database or a computation, and the stream would be built with unfold instead of iter, but the wrapper side would not change at all.

The response carries content-type: text/csv and content-disposition: attachment; filename="people.csv". The browser downloads a file called people.csv holding the three rows. The handler never mentions a header. It builds the stream, fills in the two fields, and returns.

The same wrapper serves the file download too, with a different stream type:

src/main.rs
use axum::{http::StatusCode, routing::get, Router};
use tokio_util::io::ReaderStream;

async fn file_download_handler() -> Result<
    StreamResponse<ReaderStream<tokio::fs::File>>,
    StatusCode,
> {
    let file = tokio::fs::File::open("report.bin")
        .await
        .map_err(|_| StatusCode::NOT_FOUND)?;
    Ok(StreamResponse {
        stream: ReaderStream::new(file),
        content_type: "application/octet-stream",
        filename: Some("report.bin".to_string()),
    })
}

Two handlers, two stream types, one wrapper. That is the payoff of the generic version. The header logic is written once, and every new streamed route reuses it by filling in three fields.

Adding a Length When the Size Is Known

A streamed body has no length header by default, because the stream does not know its total size. When the size is known from elsewhere, the wrapper can carry it as another field and set the header the same way it sets the content type.

For a file, the length comes from file.metadata().await, measured from the same file being streamed. The full wrapper with the length field looks like this:

src/main.rs
use axum::{
    body::{Body, Bytes},
    http::header,
    response::{IntoResponse, Response},
};
use futures_util::stream::Stream;

pub struct SizedStreamResponse<S> {
    pub stream: S,
    pub content_type: &'static str,
    pub filename: Option<String>,
    pub content_length: Option<u64>,
}

impl<S, E> IntoResponse for SizedStreamResponse<S>
where
    S: Stream<Item = Result<Bytes, E>> + Send + 'static,
    E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
    fn into_response(self) -> Response {
        let body = Body::from_stream(self.stream);
        let mut response = body.into_response();
        response.headers_mut().insert(
            header::CONTENT_TYPE,
            self.content_type.parse().unwrap(),
        );
        if let Some(name) = self.filename {
            let value = format!("attachment; filename=\"{}\"", name);
            response.headers_mut().insert(
                header::CONTENT_DISPOSITION,
                value.parse().unwrap(),
            );
        }
        if let Some(len) = self.content_length {
            response.headers_mut().insert(
                header::CONTENT_LENGTH,
                len.to_string().parse().unwrap(),
            );
        }
        response
    }
}

A live run of that pattern returned content-length: 5242880 for a 5 MiB file, and the body arrived with no chunk framing. The rule from the large-file page applies here too: the number must be exact. A wrong length corrupts the download. When the size is unknown, leave the field as None and let the response stay chunked.

Checking the File Name Before Using It in a Header

A file name that comes from a user, a database, or a file on disk is not automatically safe to put in a header. A name containing a double quote can break out of the quoted value in the disposition header. A name containing a newline can split the header into two lines, which is a classic injection hole. The wrapper should refuse names it cannot use safely.

src/main.rs
fn valid_filename(name: &str) -> bool {
    !name.is_empty()
        && !name.contains('"')
        && !name.contains('\r')
        && !name.contains('\n')
        && !name.contains('/')
        && !name.contains('\\')
        && name != ".."
}

A handler that takes a name from outside the program checks it before building the struct, and answers 400 Bad Request when the name fails:

src/main.rs
async fn named_download_handler(
    axum::extract::Path(name): axum::extract::Path<String>,
) -> Result<StreamDownload, StatusCode> {
    if !valid_filename(&name) {
        return Err(StatusCode::BAD_REQUEST);
    }
    let file = tokio::fs::File::open(format!("downloads/{}", name))
        .await
        .map_err(|_| StatusCode::NOT_FOUND)?;
    Ok(StreamDownload {
        stream: ReaderStream::new(file),
        filename: name,
        content_type: "application/octet-stream",
    })
}

The check has seven conditions: the name is not empty, and it holds no double quote, no carriage return, no newline, no forward slash, no backslash, and it is not the two dots that name a parent folder. The first four rules keep the quoted value intact and keep the header to one line. The last three keep the name a plain file name, so it cannot name a path outside the downloads folder. The handler looks the file up inside a fixed downloads folder, so a name can only pick a file in that folder. The check happens before the file is opened, so a bad name never reaches the header code or the file system at all.

Never Put Unchecked Text in a Header:

Header values are lines of text with a strict shape. A newline inside a value ends the header early, and a quote inside a quoted value ends the quoting early. Both let outside text change the meaning of the response. Validate any file name, or any other outside text, before it is formatted into a header.

A Plain Text Diagram of the Flow

Handler opens the source (file, rows, channel)
        |
        v
Handler builds the wrapper struct
  stream + content type + file name
        |
        v
Handler returns the struct
        |
        v
Axum calls into_response on the struct
        |
        v
Stream becomes a Body, headers are inserted
        |
        v
Response goes out, chunks stream to the client

The handler does the first two steps and stops. The struct does the rest. That split is the whole design: decisions about what to send live in the handler, and decisions about how it is labelled live in the struct.

Testing a Wrapper

A wrapper can be tested without a network connection, because the headers it sets are part of the response object the handler builds. A fake request through the router is enough to check them.

tests/wrapper_test.rs
use axum::{
    body::Body,
    http::{header, Request, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use tower::ServiceExt;

struct StreamDownload {
    body: Body,
}

impl IntoResponse for StreamDownload {
    fn into_response(self) -> Response {
        (
            [
                (header::CONTENT_TYPE, "text/csv"),
                (header::CONTENT_DISPOSITION, "attachment; filename=\"data.csv\""),
            ],
            self.body,
        )
            .into_response()
    }
}

async fn download_handler() -> StreamDownload {
    StreamDownload {
        body: Body::from("a,b\n1,2\n"),
    }
}

#[tokio::test]
async fn wrapper_sets_headers() {
    let app = Router::new().route("/download", get(download_handler));
    let response = app
        .oneshot(Request::builder().uri("/download").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.headers()[header::CONTENT_TYPE], "text/csv");
    assert_eq!(
        response.headers()[header::CONTENT_DISPOSITION],
        "attachment; filename=\"data.csv\""
    );
}

The test needs one development dependency:

Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

The test sends a fake request to /download and checks three things: the status is 200 OK, the content type is text/csv, and the disposition is exactly attachment; filename="data.csv". The headers are visible in the response object because into_response sets them before returning, unlike the chunked framing, which only exists on a real connection. Run it with cargo test.

A body test can go alongside it by collecting the response body and comparing it with the expected bytes, the same way the earlier pages in this cluster test streamed bodies.

Common Beginner Mistakes

Forgetting the trait implementation

// Wrong - will not compile
async fn download_handler() -> StreamDownload {
    // builds the struct, but StreamDownload has no IntoResponse impl
}

A handler can only return a type that implements IntoResponse. A struct without the implementation is an ordinary value, and Axum does not know how to turn it into a response. The compiler error points at the handler return type. The fix is the impl IntoResponse for StreamDownload block from the smallest example.

Leaving the generic bounds off

// Wrong - will not compile
impl<S, E> IntoResponse for StreamResponse<S>
where
    S: Stream<Item = Result<Bytes, E>>,
{
    fn into_response(self) -> Response {
        let body = Body::from_stream(self.stream);
        // ...
    }
}

Body::from_stream requires the stream to be Send and 'static, and the error to convert into a boxed error. An implementation that omits those bounds fails inside into_response, with an error about the trait bound not being satisfied. The fix is to carry the full bounds on the implementation, exactly as the generic example on this page shows: S: Stream<Item = Result<Bytes, E>> + Send + 'static and E: Into<Box<dyn std::error::Error + Send + Sync>>.

Unwrapping a header parse on outside text

// Wrong - panics on a bad value
response.headers_mut().insert(
    header::CONTENT_DISPOSITION,
    value.parse().unwrap(),
);

parse().unwrap() is safe when the value is built from fixed strings, because those strings are known to be valid header values. It panics when the value contains characters a header cannot hold, such as a newline from an unchecked file name. The validation function above exists to keep that panic unreachable. Validate first, then parse. Never parse outside text and unwrap the result.

Returning a bare body and setting headers at every call site

// Wrong - the same headers, copied at every route
async fn download_handler() -> (header::HeaderMap, Body) {
    // open file, build stream, build headers, return tuple
}

This works, and it is the right shape for a one-off route. It becomes a problem when three routes copy the same header code and one of them drifts. The content type changes in one place and not the others, or a new route forgets the disposition entirely. When the same headers appear twice, move them into a wrapper.

Forgetting the content type

A streamed body with no content type still reaches the client, and the bytes are still correct. But the client has to guess what the bytes mean, and browsers guess badly. A CSV file with no content type may be displayed as a page instead of downloaded. A wrapper that makes the content type a required field removes this mistake by construction. A tuple return does not, which is one more reason to prefer the wrapper when the route is a download.

A Missing Content Type Is a Silent Bug:

A missing content type produces no error, no warning, and no failed test. The download works, the bytes are right, and the client still does the wrong thing with them. Check the headers with curl -D - after wiring up a new streamed route, and confirm the content type is the one intended.

Final Complete Example

This example puts the page together. One generic wrapper, two routes: a file download and a generated CSV export.

src/main.rs
use axum::{
    body::{Body, Bytes},
    http::{header, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use futures_util::stream::{Stream, StreamExt};
use tokio_util::io::ReaderStream;

pub struct StreamResponse<S> {
    pub stream: S,
    pub content_type: &'static str,
    pub filename: Option<String>,
}

impl<S, E> IntoResponse for StreamResponse<S>
where
    S: Stream<Item = Result<Bytes, E>> + Send + 'static,
    E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
    fn into_response(self) -> Response {
        let body = Body::from_stream(self.stream);
        let mut response = body.into_response();
        response.headers_mut().insert(
            header::CONTENT_TYPE,
            self.content_type.parse().unwrap(),
        );
        if let Some(name) = self.filename {
            let value = format!("attachment; filename=\"{}\"", name);
            response.headers_mut().insert(
                header::CONTENT_DISPOSITION,
                value.parse().unwrap(),
            );
        }
        response
    }
}

async fn report_handler() -> Result<StreamResponse<ReaderStream<tokio::fs::File>>, StatusCode> {
    let file = tokio::fs::File::open("report.bin")
        .await
        .map_err(|_| StatusCode::NOT_FOUND)?;
    Ok(StreamResponse {
        stream: ReaderStream::new(file),
        content_type: "application/octet-stream",
        filename: Some("report.bin".to_string()),
    })
}

async fn export_handler() -> StreamResponse<impl Stream<Item = Result<Bytes, std::io::Error>> + Send + 'static> {
    let rows = vec!["id,name\n", "1,ada\n", "2,grace\n"];
    let ticks = futures_util::stream::iter(
        rows.into_iter()
            .map(|row| Ok::<Bytes, std::io::Error>(Bytes::from(row))),
    );
    StreamResponse {
        stream: ticks,
        content_type: "text/csv",
        filename: Some("people.csv".to_string()),
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/report", get(report_handler))
        .route("/export", get(export_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The dependencies for this example are the same three crates used across this cluster:

Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tokio-util = { version = "0.7", features = ["io"] }
futures-util = "0.3"
bytes = "1"

Try both routes:

curl -D - http://127.0.0.1:3000/report -o report.bin
curl -D - http://127.0.0.1:3000/export -o people.csv

The first reply carries content-disposition: attachment; filename="report.bin" and streams the file from disk. The second carries content-disposition: attachment; filename="people.csv" and streams three generated rows. Both replies are built by the same into_response method. The handlers differ only in where their streams come from.

Summary

A streamed response has two parts that deserve to live together: the bytes, and the facts about the bytes. The bytes come from a stream. The facts are the content type, the file name, and sometimes the length. A bare Body carries only the first part. A wrapper struct carries both, and its IntoResponse implementation is the single place where the two parts are joined.

The decision framework is short. If a streamed route is a one-off with headers that will never repeat, a tuple of headers and a body is enough. If the same headers appear on a second route, move them into a wrapper. If the routes stream from different sources, make the wrapper generic over the stream type, with the same bounds from_stream requires. And if any header value comes from outside the program, validate it before it is formatted, because a header is a line of text with a strict shape, and outside text that breaks that shape breaks the response.

The wrapper is the last piece of this cluster. A stream can now be built, fed from a file, framed on the wire, and labelled with its headers, all with the handler staying short enough to read at a glance.