Skip to main content

ringline_http/
response.rs

1use bytes::Bytes;
2
3use crate::error::HttpError;
4
5/// HTTP response.
6#[derive(Debug)]
7pub struct Response {
8    status: u16,
9    headers: Vec<(String, String)>,
10    body: Bytes,
11}
12
13impl Response {
14    pub(crate) fn new(status: u16, headers: Vec<(String, String)>, body: Bytes) -> Self {
15        Self {
16            status,
17            headers,
18            body,
19        }
20    }
21
22    /// HTTP status code (e.g. 200, 404).
23    pub fn status(&self) -> u16 {
24        self.status
25    }
26
27    /// Response headers as (name, value) pairs.
28    pub fn headers(&self) -> &[(String, String)] {
29        &self.headers
30    }
31
32    /// Get the first header value matching `name` (case-insensitive).
33    pub fn header(&self, name: &str) -> Option<&str> {
34        let lower = name.to_ascii_lowercase();
35        self.headers
36            .iter()
37            .find(|(k, _)| k.to_ascii_lowercase() == lower)
38            .map(|(_, v)| v.as_str())
39    }
40
41    /// Consume the response and return the body bytes.
42    pub fn bytes(self) -> Bytes {
43        self.body
44    }
45
46    /// Consume the response and return the body as UTF-8 text.
47    pub fn text(self) -> Result<String, HttpError> {
48        String::from_utf8(self.body.to_vec()).map_err(|_| HttpError::Parse)
49    }
50
51    /// Reference to the body bytes without consuming.
52    pub fn body(&self) -> &Bytes {
53        &self.body
54    }
55}