Skip to main content

serenade_http/
request.rs

1//! Incoming HTTP request.
2
3use crate::{AttributeBag, Headers, Method};
4
5/// Framework-agnostic HTTP request.
6///
7/// Adapters copy method, path, optional query string, headers, and body from the
8/// server crate.
9#[derive(Debug)]
10pub struct Request {
11    method: Method,
12    path: String,
13    query: Option<String>,
14    headers: Headers,
15    body: Vec<u8>,
16    attributes: AttributeBag,
17}
18
19impl Request {
20    /// Builds a request with an empty body, headers, and attributes.
21    #[must_use]
22    pub fn new(method: Method, path: impl Into<String>) -> Self {
23        Self {
24            method,
25            path: path.into(),
26            query: None,
27            headers: Headers::new(),
28            body: Vec::new(),
29            attributes: AttributeBag::new(),
30        }
31    }
32
33    /// Replaces the header map after insert.
34    #[must_use]
35    pub fn with_header(mut self, name: impl AsRef<str>, value: impl Into<String>) -> Self {
36        self.headers.insert(name, value);
37        self
38    }
39
40    /// Sets the raw body.
41    #[must_use]
42    pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
43        self.body = body.into();
44        self
45    }
46
47    /// Sets the raw query string without a leading `?`.
48    #[must_use]
49    pub fn with_query(mut self, query: impl Into<String>) -> Self {
50        let query = query.into();
51        self.query = if query.is_empty() { None } else { Some(query) };
52        self
53    }
54
55    /// HTTP method.
56    #[must_use]
57    pub const fn method(&self) -> Method {
58        self.method
59    }
60
61    /// Path (no query string).
62    #[must_use]
63    pub fn path(&self) -> &str {
64        &self.path
65    }
66
67    /// Raw query string without a leading `?`, when the adapter provided one.
68    #[must_use]
69    pub fn query(&self) -> Option<&str> {
70        self.query.as_deref()
71    }
72
73    /// Request headers.
74    #[must_use]
75    pub const fn headers(&self) -> &Headers {
76        &self.headers
77    }
78
79    /// Mutable headers (adapters and middleware).
80    pub const fn headers_mut(&mut self) -> &mut Headers {
81        &mut self.headers
82    }
83
84    /// Raw body bytes.
85    #[must_use]
86    pub fn body(&self) -> &[u8] {
87        &self.body
88    }
89
90    /// Request attributes.
91    #[must_use]
92    pub const fn attributes(&self) -> &AttributeBag {
93        &self.attributes
94    }
95
96    /// Mutable attributes (middleware, router, controller).
97    pub const fn attributes_mut(&mut self) -> &mut AttributeBag {
98        &mut self.attributes
99    }
100}