use crate::error::Error;
#[derive(Debug)]
pub struct Response {
status: u16,
headers: Vec<(String, String)>,
body: Vec<u8>,
}
impl Response {
pub(crate) fn new(status: u16, headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
Self {
status,
headers,
body,
}
}
pub fn status(&self) -> u16 {
self.status
}
pub fn headers(&self) -> &[(String, String)] {
&self.headers
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
pub fn bytes(&self) -> &[u8] {
&self.body
}
pub fn into_bytes(self) -> Vec<u8> {
self.body
}
pub fn text(&self) -> Result<&str, Error> {
std::str::from_utf8(&self.body)
.map_err(|e| Error::HttpParse(format!("Response body is not valid UTF-8: {e}")))
}
#[cfg(feature = "json")]
pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, Error> {
serde_json::from_slice(&self.body)
.map_err(|e| Error::HttpParse(format!("JSON parse error: {e}")))
}
}