Skip to main content

neco_server_core/
request.rs

1use crate::{HeaderMap, Method};
2
3/// Minimal HTTP request model.
4pub struct Request {
5    /// Request method.
6    pub method: Method,
7    /// Raw path without query string.
8    pub path: String,
9    /// Raw query string without leading `?`.
10    pub query: Option<String>,
11    /// Request headers.
12    pub headers: HeaderMap,
13    /// Fully buffered body bytes.
14    pub body: Vec<u8>,
15}
16
17impl Request {
18    /// Creates a request with empty query, headers, and body.
19    pub fn new(method: Method, path: impl Into<String>) -> Self {
20        Self {
21            method,
22            path: path.into(),
23            query: None,
24            headers: HeaderMap::new(),
25            body: Vec::new(),
26        }
27    }
28
29    /// Sets the raw query string.
30    pub fn with_query(mut self, query: impl Into<String>) -> Self {
31        self.query = Some(query.into());
32        self
33    }
34
35    /// Sets the request body.
36    pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
37        self.body = body.into();
38        self
39    }
40
41    /// Inserts or replaces a header value.
42    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
43        self.headers.insert(name, value);
44        self
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn request_builder_sets_headers() {
54        let request =
55            Request::new(Method::Get, "/x").with_header("content-type", "application/json");
56
57        assert_eq!(
58            request.headers.get("Content-Type"),
59            Some("application/json")
60        );
61    }
62}