axum::body

Function to_bytes

Source
pub async fn to_bytes(body: Body, limit: usize) -> Result<Bytes, Error>
Expand description

Converts Body into Bytes and limits the maximum size of the body.

ยงExample

use axum::body::{to_bytes, Body};

let body = Body::from(vec![1, 2, 3]);
// Use `usize::MAX` if you don't care about the maximum size.
let bytes = to_bytes(body, usize::MAX).await?;
assert_eq!(&bytes[..], &[1, 2, 3]);

You can detect if the limit was hit by checking the source of the error:

use axum::body::{to_bytes, Body};
use http_body_util::LengthLimitError;

let body = Body::from(vec![1, 2, 3]);
match to_bytes(body, 1).await {
    Ok(_bytes) => panic!("should have hit the limit"),
    Err(err) => {
        let source = std::error::Error::source(&err).unwrap();
        assert!(source.is::<LengthLimitError>());
    }
}