rustapi_core/
request.rs

1//! Request types for RustAPI
2
3use bytes::Bytes;
4use http::{request::Parts, Extensions, HeaderMap, Method, Uri, Version};
5use std::collections::HashMap;
6use std::sync::Arc;
7
8/// HTTP Request wrapper
9///
10/// Provides access to all parts of an incoming HTTP request.
11pub struct Request {
12    pub(crate) parts: Parts,
13    pub(crate) body: Option<Bytes>,
14    pub(crate) state: Arc<Extensions>,
15    pub(crate) path_params: HashMap<String, String>,
16}
17
18impl Request {
19    /// Create a new request from parts
20    pub(crate) fn new(
21        parts: Parts,
22        body: Bytes,
23        state: Arc<Extensions>,
24        path_params: HashMap<String, String>,
25    ) -> Self {
26        Self {
27            parts,
28            body: Some(body),
29            state,
30            path_params,
31        }
32    }
33
34    /// Get the HTTP method
35    pub fn method(&self) -> &Method {
36        &self.parts.method
37    }
38
39    /// Get the URI
40    pub fn uri(&self) -> &Uri {
41        &self.parts.uri
42    }
43
44    /// Get the HTTP version
45    pub fn version(&self) -> Version {
46        self.parts.version
47    }
48
49    /// Get the headers
50    pub fn headers(&self) -> &HeaderMap {
51        &self.parts.headers
52    }
53
54    /// Get request extensions
55    pub fn extensions(&self) -> &Extensions {
56        &self.parts.extensions
57    }
58
59    /// Get mutable extensions
60    pub fn extensions_mut(&mut self) -> &mut Extensions {
61        &mut self.parts.extensions
62    }
63
64    /// Get the request path
65    pub fn path(&self) -> &str {
66        self.parts.uri.path()
67    }
68
69    /// Get the query string
70    pub fn query_string(&self) -> Option<&str> {
71        self.parts.uri.query()
72    }
73
74    /// Take the body bytes (can only be called once)
75    pub fn take_body(&mut self) -> Option<Bytes> {
76        self.body.take()
77    }
78
79    /// Get path parameters
80    pub fn path_params(&self) -> &HashMap<String, String> {
81        &self.path_params
82    }
83
84    /// Get a specific path parameter
85    pub fn path_param(&self, name: &str) -> Option<&String> {
86        self.path_params.get(name)
87    }
88
89    /// Get shared state
90    pub fn state(&self) -> &Arc<Extensions> {
91        &self.state
92    }
93}
94
95impl std::fmt::Debug for Request {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        f.debug_struct("Request")
98            .field("method", &self.parts.method)
99            .field("uri", &self.parts.uri)
100            .field("version", &self.parts.version)
101            .finish()
102    }
103}