lazy_sock/
request.rs

1/* src/request.rs */
2
3use crate::router::Method;
4use std::collections::HashMap;
5use url::form_urlencoded;
6
7/// Represents an incoming HTTP-like request.
8#[derive(Debug, Clone)]
9pub struct Request {
10    method: Method,
11    path: String,
12    headers: HashMap<String, String>,
13    body: Vec<u8>,
14}
15
16impl Request {
17    /// Creates a new Request.
18    pub fn new(
19        method: Method,
20        path: String,
21        headers: HashMap<String, String>,
22        body: Vec<u8>,
23    ) -> Self {
24        Self {
25            method,
26            path,
27            headers,
28            body,
29        }
30    }
31
32    /// Gets the request method.
33    pub fn method(&self) -> &Method {
34        &self.method
35    }
36
37    /// Gets the full request path, including query string.
38    pub fn path(&self) -> &str {
39        &self.path
40    }
41
42    /// Gets all request headers.
43    pub fn headers(&self) -> &HashMap<String, String> {
44        &self.headers
45    }
46
47    /// Gets a specific header value by name.
48    pub fn header(&self, name: &str) -> Option<&String> {
49        self.headers.get(name)
50    }
51
52    /// Gets the raw request body as bytes.
53    pub fn body(&self) -> &[u8] {
54        &self.body
55    }
56
57    /// Gets the request body as a string.
58    pub fn body_string(&self) -> Result<String, std::string::FromUtf8Error> {
59        String::from_utf8(self.body.clone())
60    }
61
62    /// Parses the query parameters from the path using the `url` crate.
63    pub fn query_params(&self) -> HashMap<String, String> {
64        self.path
65            .split_once('?')
66            .map(|(_, query_string)| {
67                form_urlencoded::parse(query_string.as_bytes())
68                    .into_owned()
69                    .collect()
70            })
71            .unwrap_or_default()
72    }
73
74    /// Gets the path part of the URL, without the query string.
75    pub fn path_without_query(&self) -> &str {
76        self.path.split('?').next().unwrap_or(&self.path)
77    }
78}