1use hyper::body::Buf;
2use hyper::{header::HeaderValue, Body, HeaderMap, StatusCode};
34use crate::{Error, HeaderError};
56pub struct ErrorBody {
7 body: Body,
8}
910impl ErrorBody {
11pub fn new(body: Body) -> Self {
12Self { body }
13 }
1415/// Returns the body of the response as a vector of bytes.
16 ///
17 /// Caution: This method reads the entire body into memory. You should only use this method if
18 /// you know the response is of a reasonable size.
19pub async fn body_bytes(self) -> Result<Vec<u8>, Error> {
20let buf = match hyper::body::aggregate(self.body).await {
21Ok(buf) => buf,
22Err(err) => return Err(Error::HttpStream(Box::new(err))),
23 };
2425Ok(buf.chunk().to_vec())
26 }
27}
2829impl std::fmt::Debug for ErrorBody {
30fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 f.debug_struct("ErrorBody").finish()
32 }
33}
3435#[derive(Clone, Debug, Eq, PartialEq)]
36pub struct Response {
37 status_code: StatusCode,
38 headers: HeaderMap<HeaderValue>,
39}
4041impl Response {
42pub fn new(status_code: StatusCode, headers: HeaderMap<HeaderValue>) -> Self {
43Self {
44 status_code,
45 headers,
46 }
47 }
4849/// Returns the status code of this response.
50pub fn status(&self) -> u16 {
51self.status_code.as_u16()
52 }
5354/// Returns the list of header keys present in this response.
55pub fn get_header_keys(&self) -> Vec<&str> {
56self.headers.keys().map(|key| key.as_str()).collect()
57 }
5859/// Returns the value of a header.
60 ///
61 /// If the header contains more than one value, only the first value is returned. Refer to
62 /// [`get_header_values`] for a method that returns all values.
63pub fn get_header_value(&self, key: &str) -> std::result::Result<Option<&str>, HeaderError> {
64if let Some(value) = self.headers.get(key) {
65 value
66 .to_str()
67 .map(Some)
68 .map_err(|e| HeaderError::new(Box::new(e)))
69 } else {
70Ok(None)
71 }
72 }
7374/// Returns all values for a header.
75 ///
76 /// If the header contains only one value, it will be returned as a single-element vector.
77 /// Refer to [`get_header_value`] for a method that returns only a single value.
78pub fn get_header_values(&self, key: &str) -> std::result::Result<Vec<&str>, HeaderError> {
79self.headers
80 .get_all(key)
81 .iter()
82 .map(|value| value.to_str().map_err(|e| HeaderError::new(Box::new(e))))
83 .collect()
84 }
85}