/rust/registry/src/index.crates.io-1949cf8c6b5b557f/axum-0.7.9/src/body/mod.rs
Line | Count | Source |
1 | | //! HTTP body utilities. |
2 | | |
3 | | #[doc(no_inline)] |
4 | | pub use http_body::Body as HttpBody; |
5 | | |
6 | | #[doc(no_inline)] |
7 | | pub use bytes::Bytes; |
8 | | |
9 | | #[doc(inline)] |
10 | | pub use axum_core::body::{Body, BodyDataStream}; |
11 | | |
12 | | use http_body_util::{BodyExt, Limited}; |
13 | | |
14 | | /// Converts [`Body`] into [`Bytes`] and limits the maximum size of the body. |
15 | | /// |
16 | | /// # Example |
17 | | /// |
18 | | /// ```rust |
19 | | /// use axum::body::{to_bytes, Body}; |
20 | | /// |
21 | | /// # async fn foo() -> Result<(), axum_core::Error> { |
22 | | /// let body = Body::from(vec![1, 2, 3]); |
23 | | /// // Use `usize::MAX` if you don't care about the maximum size. |
24 | | /// let bytes = to_bytes(body, usize::MAX).await?; |
25 | | /// assert_eq!(&bytes[..], &[1, 2, 3]); |
26 | | /// # Ok(()) |
27 | | /// # } |
28 | | /// ``` |
29 | | /// |
30 | | /// You can detect if the limit was hit by checking the source of the error: |
31 | | /// |
32 | | /// ```rust |
33 | | /// use axum::body::{to_bytes, Body}; |
34 | | /// use http_body_util::LengthLimitError; |
35 | | /// |
36 | | /// # #[tokio::main] |
37 | | /// # async fn main() { |
38 | | /// let body = Body::from(vec![1, 2, 3]); |
39 | | /// match to_bytes(body, 1).await { |
40 | | /// Ok(_bytes) => panic!("should have hit the limit"), |
41 | | /// Err(err) => { |
42 | | /// let source = std::error::Error::source(&err).unwrap(); |
43 | | /// assert!(source.is::<LengthLimitError>()); |
44 | | /// } |
45 | | /// } |
46 | | /// # } |
47 | | /// ``` |
48 | 0 | pub async fn to_bytes(body: Body, limit: usize) -> Result<Bytes, axum_core::Error> { |
49 | 0 | Limited::new(body, limit) |
50 | 0 | .collect() |
51 | 0 | .await |
52 | 0 | .map(|col| col.to_bytes()) |
53 | 0 | .map_err(axum_core::Error::new) |
54 | 0 | } |