Skip to main content

serenade_http_client/
response.rs

1//! Outbound response.
2
3use std::collections::BTreeMap;
4
5/// Outbound HTTP response.
6#[derive(Clone, Debug, Eq, PartialEq)]
7pub struct ClientResponse {
8    status: u16,
9    headers: BTreeMap<String, String>,
10    body: Vec<u8>,
11}
12
13impl ClientResponse {
14    /// Builds a response.
15    #[must_use]
16    pub const fn new(status: u16) -> Self {
17        Self {
18            status,
19            headers: BTreeMap::new(),
20            body: Vec::new(),
21        }
22    }
23
24    /// Sets a header (name stored lowercased).
25    #[must_use]
26    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
27        self.headers
28            .insert(name.into().to_ascii_lowercase(), value.into());
29        self
30    }
31
32    /// Sets the body bytes.
33    #[must_use]
34    pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
35        self.body = body.into();
36        self
37    }
38
39    /// Sets a UTF-8 body.
40    #[must_use]
41    pub fn body_text(self, text: impl Into<String>) -> Self {
42        self.body(text.into().into_bytes())
43    }
44
45    /// Status code.
46    #[must_use]
47    pub const fn status(&self) -> u16 {
48        self.status
49    }
50
51    /// True when status is 2xx.
52    #[must_use]
53    pub const fn is_success(&self) -> bool {
54        self.status >= 200 && self.status < 300
55    }
56
57    /// Headers (lowercased names).
58    #[must_use]
59    pub const fn headers(&self) -> &BTreeMap<String, String> {
60        &self.headers
61    }
62
63    /// Header value by name (case-insensitive).
64    #[must_use]
65    pub fn header_value(&self, name: &str) -> Option<&str> {
66        self.headers
67            .get(&name.to_ascii_lowercase())
68            .map(String::as_str)
69    }
70
71    /// Body bytes.
72    #[must_use]
73    pub fn body_bytes(&self) -> &[u8] {
74        &self.body
75    }
76
77    /// Body as lossy UTF-8.
78    #[must_use]
79    pub fn body_text_lossy(&self) -> String {
80        String::from_utf8_lossy(&self.body).into_owned()
81    }
82}