pub struct BodyReader<B> { /* private fields */ }Expand description
Convenient wrapper for reading Body content from http::Response.
It is useful in the most common response body reading cases.
Implementations§
Source§impl<B> BodyReader<B>
impl<B> BodyReader<B>
Sourcepub async fn bytes(self) -> Result<Bytes, <B as Body>::Error>
pub async fn bytes(self) -> Result<Bytes, <B as Body>::Error>
Reads the full response body as Bytes.
§Example
use http::Response;
use http_body_reader::ResponseExt as _;
use http_body_util::Full;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Create a new response with the given text as the body.
let message = b"Hello world";
let response = Response::builder().body(Full::new(message.as_ref()))?;
// Read the response body as bytes and check that it matches the original message.
assert_eq!(response.body_reader().bytes().await?, message.as_ref());
Ok(())
}Sourcepub async fn utf8(
self,
) -> Result<String, BodyReaderError<<B as Body>::Error, FromUtf8Error>>
pub async fn utf8( self, ) -> Result<String, BodyReaderError<<B as Body>::Error, FromUtf8Error>>
Reads the full response text.
§Note
The method will only attempt to decode the response as UTF-8, regardless of the
Content-Type header.
§Errors
This method fails if the response body cannot be decoded as UTF-8.
§Example
use http::Response;
use http_body_reader::ResponseExt as _;
use http_body_util::Full;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Create a new response with the given text as the body.
let message = "Hello world";
let response = Response::builder().body(Full::new(message.as_ref()))?;
// Read the response body as UTF-8 and check that it matches the original message.
assert_eq!(response.body_reader().utf8().await?, message);
Ok(())
}Sourcepub async fn json<T>(
self,
) -> Result<T, BodyReaderError<<B as Body>::Error, Error>>
pub async fn json<T>( self, ) -> Result<T, BodyReaderError<<B as Body>::Error, Error>>
Deserializes the response body as JSON.
§Errors
This method fails whenever the response body is not valid JSON
or it cannot be properly deserialized to the target type T.
§Examples
use http::Response;
use http_body_reader::ResponseExt as _;
use http_body_util::Full;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct SomeInfo {
id: u32,
name: String,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let info = SomeInfo {
id: 1234,
name: "Alice".to_string(),
};
// Create a response with JSON body.
let data = serde_json::to_vec(&info)?;
let response = Response::builder().body(Full::new(data.as_ref()))?;
// Read the response body as JSON and check that it matches the original info.
assert_eq!(response.body_reader().json::<SomeInfo>().await?, info);
Ok(())
}Sourcepub async fn form<T>(
self,
) -> Result<T, BodyReaderError<<B as Body>::Error, Error>>
pub async fn form<T>( self, ) -> Result<T, BodyReaderError<<B as Body>::Error, Error>>
Deserializes the response body as form data.
§Errors
This method fails whenever the response body is not valid form data
or it cannot be properly deserialized to the target type T.
§Examples
use http::Response;
use http_body_reader::ResponseExt as _;
use http_body_util::Full;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct SomeInfo {
id: u32,
name: String,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let info = SomeInfo {
id: 1234,
name: "Alice".to_string(),
};
// Create a response with form data.
let data = serde_urlencoded::to_string(&info)?;
let response = Response::builder().body(Full::new(data.as_ref()))?;
// Read the response body as form data and check that it matches the original info.
assert_eq!(response.body_reader().form::<SomeInfo>().await?, info);
Ok(())
}Sourcepub fn map<F, T>(self, f: F) -> BodyReader<T>
pub fn map<F, T>(self, f: F) -> BodyReader<T>
Maps the body content using the provided function.
§Example
use http::Response;
use http_body_reader::ResponseExt as _;
use http_body_util::{Full, Limited};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Create a response with a body
let response = Response::builder().body(Full::new("Lorem ipsum dolor sit amet".as_ref()))?;
// Create a body reader with a limit of 8 bytes
let body_reader = response.body_reader().map(|body| Limited::new(body, 8));
// Make sure the body reader returns an error when the limit is exceeded.
assert_eq!(
body_reader.utf8().await.unwrap_err().to_string(),
"length limit exceeded"
);
Ok(())
}Trait Implementations§
Source§impl<B> Clone for BodyReader<B>where
B: Clone,
impl<B> Clone for BodyReader<B>where
B: Clone,
Source§fn clone(&self) -> BodyReader<B>
fn clone(&self) -> BodyReader<B>
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreSource§impl<B> Debug for BodyReader<B>where
B: Debug,
impl<B> Debug for BodyReader<B>where
B: Debug,
Source§impl<B> From<Response<B>> for BodyReader<B>
impl<B> From<Response<B>> for BodyReader<B>
Source§fn from(response: Response<B>) -> BodyReader<B>
fn from(response: Response<B>) -> BodyReader<B>
Converts to this type from the input type.
Auto Trait Implementations§
impl<B> Freeze for BodyReader<B>where
B: Freeze,
impl<B> RefUnwindSafe for BodyReader<B>where
B: RefUnwindSafe,
impl<B> Send for BodyReader<B>where
B: Send,
impl<B> Sync for BodyReader<B>where
B: Sync,
impl<B> Unpin for BodyReader<B>where
B: Unpin,
impl<B> UnwindSafe for BodyReader<B>where
B: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more