neco-server-core 0.1.0

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

/// Minimal HTTP request model.
pub struct Request {
    /// Request method.
    pub method: Method,
    /// Raw path without query string.
    pub path: String,
    /// Raw query string without leading `?`.
    pub query: Option<String>,
    /// Request headers.
    pub headers: HeaderMap,
    /// Fully buffered body bytes.
    pub body: Vec<u8>,
}

impl Request {
    /// Creates a request with empty query, headers, and body.
    pub fn new(method: Method, path: impl Into<String>) -> Self {
        Self {
            method,
            path: path.into(),
            query: None,
            headers: HeaderMap::new(),
            body: Vec::new(),
        }
    }

    /// Sets the raw query string.
    pub fn with_query(mut self, query: impl Into<String>) -> Self {
        self.query = Some(query.into());
        self
    }

    /// Sets the request body.
    pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
        self.body = body.into();
        self
    }

    /// Inserts or replaces a 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 request_builder_sets_headers() {
        let request =
            Request::new(Method::Get, "/x").with_header("content-type", "application/json");

        assert_eq!(
            request.headers.get("Content-Type"),
            Some("application/json")
        );
    }
}