neco-server-core 0.1.0

core http primitives for neco-server
Documentation
use crate::{HeaderMap, StatusCode};

/// Minimal HTTP response model.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Response {
    /// HTTP status code.
    pub status: StatusCode,
    /// Response headers.
    pub headers: HeaderMap,
    /// Fully buffered response body.
    pub body: Vec<u8>,
}

impl Response {
    /// Creates a response with the given status and empty headers/body.
    pub fn new(status: StatusCode) -> Self {
        Self {
            status,
            headers: HeaderMap::new(),
            body: Vec::new(),
        }
    }

    /// Convenience constructor for text or binary body payloads.
    pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
        self.body = body.into();
        self
    }

    /// Inserts or replaces a response header value.
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(name, value);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn response_builder_sets_headers_and_body() {
        let response = Response::new(StatusCode::OK)
            .with_header("content-type", "text/plain")
            .with_body(b"ok".to_vec());

        assert_eq!(response.status, StatusCode::OK);
        assert_eq!(response.headers.get("Content-Type"), Some("text/plain"));
        assert_eq!(response.body, b"ok");
    }
}