From 3c7cf8184057964d7eb0db1aa48422a09cfeeedd Mon Sep 17 00:00:00 2001 From: Ethra <107059409+ItsEthra@users.noreply.github.com> Date: Wed, 29 Nov 2023 13:31:15 +0300 Subject: [PATCH] Add utility function to convert body into bytes (#2373) Co-authored-by: David Pedersen --- axum/CHANGELOG.md | 4 +++- axum/src/body/mod.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/axum/CHANGELOG.md b/axum/CHANGELOG.md index 0e4c8b20d6..4012f6034d 100644 --- a/axum/CHANGELOG.md +++ b/axum/CHANGELOG.md @@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 # Unreleased -- None. +- **added:** Add `axum::body::to_bytes` ([#2373]) + +[#2373]: https://github.com/tokio-rs/axum/pull/2373 # 0.7.1 (27. November, 2023) diff --git a/axum/src/body/mod.rs b/axum/src/body/mod.rs index 0e3d478179..b52db8231a 100644 --- a/axum/src/body/mod.rs +++ b/axum/src/body/mod.rs @@ -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(()) +/// # } +/// ``` +/// +/// 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::()); +/// } +/// } +/// # } +/// ``` +pub async fn to_bytes(body: Body, limit: usize) -> Result { + Limited::new(body, limit) + .collect() + .await + .map(|col| col.to_bytes()) + .map_err(axum_core::Error::new) +}