Skip to content

Commit 0460cd9

Browse files
docs(body): add example for to_bytes()
cc hyperium#2201
1 parent e6b2cbd commit 0460cd9

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/body/to_bytes.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,36 @@ use super::HttpBody;
1313
/// Care needs to be taken if the remote is untrusted. The function doesn't implement any length
1414
/// checks and an malicious peer might make it consume arbitrary amounts of memory. Checking the
1515
/// `Content-Length` is a possibility, but it is not strictly mandated to be present.
16+
///
17+
/// # Example
18+
///
19+
/// ```
20+
/// # async fn doc() -> hyper::Result<()> {
21+
/// use hyper::{body::HttpBody};
22+
///
23+
/// # let request = hyper::Request::builder()
24+
/// # .method(hyper::Method::POST)
25+
/// # .uri("http://httpbin.org/post")
26+
/// # .header("content-type", "application/json")
27+
/// # .body(hyper::Body::from(r#"{"library":"hyper"}"#)).unwrap();
28+
/// # let client = hyper::Client::new();
29+
/// let response = client.request(request).await?;
30+
///
31+
/// const MAX_ALLOWED_RESPONSE_SIZE: u64 = 1024;
32+
///
33+
/// let response_content_length = match response.body().size_hint().upper() {
34+
/// Some(v) => v,
35+
/// None => MAX_ALLOWED_RESPONSE_SIZE + 1 // Just to protect ourselves from a malicious response
36+
/// };
37+
///
38+
/// if response_content_length < MAX_ALLOWED_RESPONSE_SIZE {
39+
/// let body_bytes = hyper::body::to_bytes(response.into_body()).await?;
40+
/// println!("body: {:?}", body_bytes);
41+
/// }
42+
///
43+
/// # Ok(())
44+
/// # }
45+
/// ```
1646
pub async fn to_bytes<T>(body: T) -> Result<Bytes, T::Error>
1747
where
1848
T: HttpBody,

0 commit comments

Comments
 (0)