1use hyper::{Body, Method, Request as HyperRequest, Uri};
2use serde_json::Value;
3use std::collections::HashMap;
4use std::net::SocketAddr;
5
6#[derive(Debug)]
7pub struct Request {
8 pub method: Method,
9 pub uri: Uri,
10 pub headers: hyper::HeaderMap,
11 pub body: Body,
12 pub params: HashMap<String, String>,
13 pub query: HashMap<String, String>,
14 pub json_body: Option<Value>,
15 pub form_data_cache: Option<HashMap<String, String>>,
16 pub request_id: String,
17 pub user_id: Option<String>,
19 pub user_roles: Vec<String>,
20 pub session: Option<crate::session::SessionHandle>,
21 pub extensions: hyper::http::Extensions,
22 pub remote_addr: Option<SocketAddr>,
23}
24
25impl Request {
26 pub async fn from_hyper(
27 req: HyperRequest<Body>,
28 ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
29 Self::from_hyper_with_addr(req, None).await
30 }
31
32 pub async fn from_hyper_with_addr(
33 req: HyperRequest<Body>,
34 remote_addr: Option<SocketAddr>,
35 ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
36 let (parts, body) = req.into_parts();
37 let query = Self::parse_query(&parts.uri);
38 let request_id = Self::resolve_request_id(&parts.headers);
39
40 Ok(Request {
41 method: parts.method,
42 uri: parts.uri,
43 headers: parts.headers,
44 body,
45 params: HashMap::new(),
46 query,
47 json_body: None,
48 form_data_cache: None,
49 request_id,
50 user_id: None,
51 user_roles: Vec::new(),
52 session: None,
53 extensions: parts.extensions,
54 remote_addr,
55 })
56 }
57
58 pub async fn json(&mut self) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
59 if self.json_body.is_none() {
60 let body_bytes =
61 hyper::body::to_bytes(std::mem::replace(&mut self.body, hyper::Body::empty()))
62 .await?;
63 if !body_bytes.is_empty() {
64 self.json_body = Some(serde_json::from_slice(&body_bytes)?);
65 }
66 self.body = hyper::Body::from(body_bytes);
68 }
69 Ok(self.json_body.clone().unwrap_or(Value::Null))
70 }
71
72 pub async fn form_data(
73 &mut self,
74 ) -> Result<HashMap<String, String>, Box<dyn std::error::Error + Send + Sync>> {
75 if self.form_data_cache.is_none() {
76 let body = std::mem::replace(&mut self.body, hyper::Body::empty());
77 let body_bytes = hyper::body::to_bytes(body).await?;
78 self.body = hyper::Body::from(body_bytes.clone());
79 if !body_bytes.is_empty() {
80 let raw = String::from_utf8_lossy(&body_bytes);
81 let mut map = HashMap::new();
82 for pair in raw.split('&') {
83 if pair.is_empty() {
84 continue;
85 }
86
87 let mut parts = pair.splitn(2, '=');
88 let key = decode_form_component(parts.next().unwrap_or_default());
89 let value = decode_form_component(parts.next().unwrap_or_default());
90 map.insert(key, value);
91 }
92 self.form_data_cache = Some(map);
93 } else {
94 self.form_data_cache = Some(HashMap::new());
95 }
96 }
97 Ok(self.form_data_cache.clone().unwrap_or_default())
98 }
99
100 pub fn request_id(&self) -> &str {
102 &self.request_id
103 }
104
105 pub const fn request_id_header() -> &'static str {
107 "X-Request-ID"
108 }
109
110 fn resolve_request_id(headers: &hyper::HeaderMap) -> String {
111 headers
112 .get(Self::request_id_header())
113 .and_then(|value| value.to_str().ok())
114 .filter(|value| !value.is_empty() && value.len() <= 128)
115 .map(ToOwned::to_owned)
116 .unwrap_or_else(|| uuid::Uuid::new_v4().to_string())
117 }
118
119 pub fn param(&self, key: &str) -> Option<&String> {
120 self.params.get(key)
121 }
122
123 pub fn query_param(&self, key: &str) -> Option<&String> {
124 self.query.get(key)
125 }
126
127 pub fn header(&self, key: &str) -> Option<&str> {
129 self.headers.get(key).and_then(|v| v.to_str().ok())
130 }
131
132 pub fn is_json(&self) -> bool {
134 self.header("content-type")
135 .map(|ct| ct.contains("application/json"))
136 .unwrap_or(false)
137 }
138
139 pub fn is_ajax(&self) -> bool {
141 self.header("x-requested-with")
142 .map(|v| v.eq_ignore_ascii_case("xmlhttprequest"))
143 .unwrap_or(false)
144 }
145
146 pub async fn body_bytes(
148 &mut self,
149 ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
150 let body = std::mem::replace(&mut self.body, hyper::Body::empty());
151 let body_bytes = hyper::body::to_bytes(body).await?;
152 self.body = hyper::Body::from(body_bytes.clone());
154 Ok(body_bytes.to_vec())
155 }
156
157 fn parse_query(uri: &Uri) -> HashMap<String, String> {
158 let mut query = HashMap::new();
159 if let Some(query_str) = uri.query() {
160 for pair in query_str.split('&') {
161 if let Some((key, value)) = pair.split_once('=') {
162 query.insert(
163 percent_encoding::percent_decode_str(key)
164 .decode_utf8_lossy()
165 .to_string(),
166 percent_encoding::percent_decode_str(value)
167 .decode_utf8_lossy()
168 .to_string(),
169 );
170 }
171 }
172 }
173 query
174 }
175}
176
177fn decode_form_component(value: &str) -> String {
178 percent_encoding::percent_decode_str(&value.replace('+', " "))
179 .decode_utf8_lossy()
180 .into_owned()
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[tokio::test]
188 async fn form_data_preserves_encoded_delimiters_and_body() {
189 let req = hyper::Request::builder()
190 .method(Method::POST)
191 .uri("/submit")
192 .body(Body::from("title=fish%26chips¬e=a%3Db+c"))
193 .unwrap();
194
195 let mut req = Request::from_hyper(req).await.unwrap();
196 let form = req.form_data().await.unwrap();
197
198 assert_eq!(form.get("title"), Some(&"fish&chips".to_string()));
199 assert_eq!(form.get("note"), Some(&"a=b c".to_string()));
200 assert_eq!(
201 String::from_utf8(req.body_bytes().await.unwrap()).unwrap(),
202 "title=fish%26chips¬e=a%3Db+c"
203 );
204 }
205}