Skip to main content

neco_server_core/
response.rs

1use crate::{HeaderMap, StatusCode};
2
3/// Minimal HTTP response model.
4#[derive(Clone, Debug, PartialEq, Eq)]
5pub struct Response {
6    /// HTTP status code.
7    pub status: StatusCode,
8    /// Response headers.
9    pub headers: HeaderMap,
10    /// Fully buffered response body.
11    pub body: Vec<u8>,
12}
13
14impl Response {
15    /// Creates a response with the given status and empty headers/body.
16    pub fn new(status: StatusCode) -> Self {
17        Self {
18            status,
19            headers: HeaderMap::new(),
20            body: Vec::new(),
21        }
22    }
23
24    /// Convenience constructor for text or binary body payloads.
25    pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
26        self.body = body.into();
27        self
28    }
29
30    /// Inserts or replaces a response header value.
31    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
32        self.headers.insert(name, value);
33        self
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn response_builder_sets_headers_and_body() {
43        let response = Response::new(StatusCode::OK)
44            .with_header("content-type", "text/plain")
45            .with_body(b"ok".to_vec());
46
47        assert_eq!(response.status, StatusCode::OK);
48        assert_eq!(response.headers.get("Content-Type"), Some("text/plain"));
49        assert_eq!(response.body, b"ok");
50    }
51}