eventsource_client/
response.rs

1use hyper::body::Buf;
2use hyper::{header::HeaderValue, Body, HeaderMap, StatusCode};
3
4use crate::{Error, HeaderError};
5
6pub struct ErrorBody {
7    body: Body,
8}
9
10impl ErrorBody {
11    pub fn new(body: Body) -> Self {
12        Self { body }
13    }
14
15    /// 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.
19    pub async fn body_bytes(self) -> Result<Vec<u8>, Error> {
20        let buf = match hyper::body::aggregate(self.body).await {
21            Ok(buf) => buf,
22            Err(err) => return Err(Error::HttpStream(Box::new(err))),
23        };
24
25        Ok(buf.chunk().to_vec())
26    }
27}
28
29impl std::fmt::Debug for ErrorBody {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        f.debug_struct("ErrorBody").finish()
32    }
33}
34
35#[derive(Clone, Debug, Eq, PartialEq)]
36pub struct Response {
37    status_code: StatusCode,
38    headers: HeaderMap<HeaderValue>,
39}
40
41impl Response {
42    pub fn new(status_code: StatusCode, headers: HeaderMap<HeaderValue>) -> Self {
43        Self {
44            status_code,
45            headers,
46        }
47    }
48
49    /// Returns the status code of this response.
50    pub fn status(&self) -> u16 {
51        self.status_code.as_u16()
52    }
53
54    /// Returns the list of header keys present in this response.
55    pub fn get_header_keys(&self) -> Vec<&str> {
56        self.headers.keys().map(|key| key.as_str()).collect()
57    }
58
59    /// 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.
63    pub fn get_header_value(&self, key: &str) -> std::result::Result<Option<&str>, HeaderError> {
64        if 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 {
70            Ok(None)
71        }
72    }
73
74    /// 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.
78    pub fn get_header_values(&self, key: &str) -> std::result::Result<Vec<&str>, HeaderError> {
79        self.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}