Skip to main content

serenade_http/
response.rs

1//! Outgoing HTTP response.
2
3use crate::Headers;
4
5/// Framework-agnostic HTTP response.
6#[derive(Clone, Debug, Eq, PartialEq)]
7pub struct Response {
8    status: u16,
9    headers: Headers,
10    body: Vec<u8>,
11}
12
13impl Response {
14    /// Empty body at `status`.
15    #[must_use]
16    pub fn new(status: u16) -> Self {
17        Self {
18            status,
19            headers: Headers::new(),
20            body: Vec::new(),
21        }
22    }
23
24    /// UTF-8 body with `text/plain; charset=utf-8`.
25    #[must_use]
26    pub fn text(status: u16, body: impl Into<String>) -> Self {
27        Self::new(status)
28            .with_header("content-type", "text/plain; charset=utf-8")
29            .with_body(body.into().into_bytes())
30    }
31
32    /// Adds or replaces a header.
33    #[must_use]
34    pub fn with_header(mut self, name: impl AsRef<str>, value: impl Into<String>) -> Self {
35        self.headers.insert(name, value);
36        self
37    }
38
39    /// Sets the raw body.
40    #[must_use]
41    pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
42        self.body = body.into();
43        self
44    }
45
46    /// Status code.
47    #[must_use]
48    pub const fn status(&self) -> u16 {
49        self.status
50    }
51
52    /// Response headers.
53    #[must_use]
54    pub const fn headers(&self) -> &Headers {
55        &self.headers
56    }
57
58    /// Mutable headers (middleware).
59    pub const fn headers_mut(&mut self) -> &mut Headers {
60        &mut self.headers
61    }
62
63    /// Raw body bytes.
64    #[must_use]
65    pub fn body(&self) -> &[u8] {
66        &self.body
67    }
68
69    /// Body as UTF-8 when valid.
70    #[must_use]
71    pub fn body_str(&self) -> Option<&str> {
72        std::str::from_utf8(&self.body).ok()
73    }
74}