Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added utility function to convert body into bytes #2373

Merged
merged 6 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion axum/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

# Unreleased

- None.
- **added:** Add `axum::body::to_bytes` ([#2373])
ItsEthra marked this conversation as resolved.
Show resolved Hide resolved

# 0.7.1 (27. November, 2023)

Expand Down
44 changes: 44 additions & 0 deletions axum/src/body/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,47 @@ pub use bytes::Bytes;

#[doc(inline)]
pub use axum_core::body::Body;

use http_body_util::{BodyExt, Limited};

/// Converts [`Body`] into [`Bytes`] and limits the maximum size of the body.
///
/// # Example
///
/// ```rust
/// use axum::body::{to_bytes, Body};
///
/// # async fn foo() -> Result<(), axum_core::Error> {
/// 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]);
/// # Ok(())
/// # }
/// ```
ItsEthra marked this conversation as resolved.
Show resolved Hide resolved
///
/// You can detect if the limit was hit by checking the source of the error:
///
/// ```rust
/// use axum::body::{to_bytes, Body};
/// use http_body_util::LengthLimitError;
///
/// # #[tokio::main]
/// # async fn main() {
/// 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>());
/// }
/// }
/// # }
/// ```
pub async fn to_bytes(body: Body, limit: usize) -> Result<Bytes, axum_core::Error> {
Limited::new(body, limit)
.collect()
.await
.map(|col| col.to_bytes())
.map_err(axum_core::Error::new)
}