use bytes::{Bytes, BytesMut};
use http::{Extensions, HeaderMap, HeaderValue, StatusCode, Version};
use monoio_http::{
common::body::{Body, StreamHint},
h1::payload::BoxedFramedPayload,
};
pub struct ClientResponse {
status: StatusCode,
version: Version,
headers: HeaderMap<HeaderValue>,
extensions: Extensions,
body: BoxedFramedPayload,
}
impl ClientResponse {
pub fn new(inner: http::Response<BoxedFramedPayload>) -> Self {
let (head, body) = inner.into_parts();
Self {
status: head.status,
version: head.version,
headers: head.headers,
extensions: head.extensions,
body,
}
}
#[inline]
pub fn status(&self) -> StatusCode {
self.status
}
#[inline]
pub fn version(&self) -> Version {
self.version
}
#[inline]
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
#[inline]
pub fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.headers
}
pub fn extensions(&self) -> &http::Extensions {
&self.extensions
}
pub fn extensions_mut(&mut self) -> &mut http::Extensions {
&mut self.extensions
}
pub async fn bytes(self) -> crate::Result<Bytes> {
let mut body = self.body;
if body.stream_hint() == StreamHint::None {
return Ok(Bytes::new());
}
let mut data = BytesMut::new();
while let Some(res) = body.next_data().await {
data.extend(res?);
}
Ok(data.freeze())
}
pub fn raw_body(self) -> BoxedFramedPayload {
self.body
}
pub async fn json<T: serde::de::DeserializeOwned>(self) -> crate::Result<T> {
let bytes = self.bytes().await?;
let d = serde_json::from_slice(&bytes)?;
Ok(d)
}
}