use crate::error::BaseError;
use reqwest::header::HeaderMap;
use reqwest::Response as ReqwestResponse;
pub struct Response {
response: ReqwestResponse,
max_response_bytes: usize,
}
impl Response {
pub(crate) fn new(response: ReqwestResponse, max_response_bytes: usize) -> Self {
Self {
response,
max_response_bytes,
}
}
pub fn status(&self) -> u16 {
self.response.status().as_u16()
}
pub fn is_success(&self) -> bool {
self.response.status().is_success()
}
pub fn headers(&self) -> &HeaderMap {
self.response.headers()
}
pub fn url(&self) -> &str {
self.response.url().as_str()
}
pub async fn text(self) -> Result<String, BaseError> {
let charset = self
.response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.split(';').find_map(|p| p.trim().strip_prefix("charset=")))
.and_then(|label| encoding_rs::Encoding::for_label(label.trim().as_bytes()))
.unwrap_or(encoding_rs::UTF_8);
let body = self.read_body_limited().await?;
let (text, _, _) = charset.decode(&body);
Ok(text.into_owned())
}
pub async fn bytes(self) -> Result<Vec<u8>, BaseError> {
self.read_body_limited().await
}
pub async fn json<T: serde::de::DeserializeOwned>(self) -> Result<T, BaseError> {
let body = self.read_body_limited().await?;
serde_json::from_slice(&body).map_err(|e| BaseError::JsonDeserializeFailed(e.to_string()))
}
async fn read_body_limited(mut self) -> Result<Vec<u8>, BaseError> {
let limit = self.max_response_bytes;
if let Some(len) = self.response.content_length() {
if len > limit as u64 {
return Err(BaseError::HttpResponseTooLarge {
limit,
actual: Some(len),
});
}
}
let mut buf: Vec<u8> = Vec::with_capacity(limit.min(64 * 1024));
while let Some(chunk) = self
.response
.chunk()
.await
.map_err(|e| BaseError::HttpResponseParseFailed(e.to_string()))?
{
if buf.len() + chunk.len() > limit {
return Err(BaseError::HttpResponseTooLarge {
limit,
actual: None,
});
}
buf.extend_from_slice(&chunk);
}
Ok(buf)
}
}