Skip to main content

eventsource_client/
response.rs

1use http::{HeaderMap, HeaderValue, StatusCode};
2
3use crate::HeaderError;
4use launchdarkly_sdk_transport::ByteStream;
5
6/// Represents an error response body as a stream of bytes.
7///
8/// The body is provided as a stream so that users can read error details if needed.
9/// For large error responses, the stream allows processing without loading the entire
10/// response into memory.
11pub struct ErrorBody {
12    body: ByteStream,
13}
14
15impl ErrorBody {
16    /// Create a new ErrorBody from a ByteStream
17    pub fn new(body: ByteStream) -> Self {
18        Self { body }
19    }
20
21    /// Consume this ErrorBody and return the underlying ByteStream
22    pub fn into_stream(self) -> ByteStream {
23        self.body
24    }
25}
26
27impl std::fmt::Debug for ErrorBody {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        f.debug_struct("ErrorBody")
30            .field("body", &"<stream>")
31            .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}