1use crate::cookies::Cookies;
4use crate::error::{Error, Result};
5use serde::de::DeserializeOwned;
6use std::collections::HashMap;
7use std::sync::{Arc, OnceLock};
8
9#[derive(Debug, Clone)]
11pub struct Params {
12 inner: HashMap<String, String>,
13}
14
15impl Params {
16 pub fn new() -> Self {
17 Self {
18 inner: HashMap::new(),
19 }
20 }
21
22 pub fn insert(&mut self, key: String, value: String) {
23 self.inner.insert(key, value);
24 }
25
26 pub fn get(&self, key: &str) -> Result<&str> {
27 self.inner
28 .get(key)
29 .map(|s| s.as_str())
30 .ok_or_else(|| Error::bad_request(format!("Missing param: {}", key)))
31 }
32
33 pub fn get_opt(&self, key: &str) -> Option<&str> {
34 self.inner.get(key).map(|s| s.as_str())
35 }
36
37 pub fn parse<T: std::str::FromStr>(&self, key: &str) -> Result<T> {
41 self.get(key)?
42 .parse()
43 .map_err(|_| Error::bad_request(format!("Invalid path parameter '{}'", key)))
44 }
45}
46
47impl Default for Params {
48 fn default() -> Self {
49 Self::new()
50 }
51}
52
53#[derive(Debug, Clone)]
55pub struct Query {
56 inner: HashMap<String, String>,
57 raw: String,
58}
59
60impl Query {
61 pub fn new() -> Self {
62 Self {
63 inner: HashMap::new(),
64 raw: String::new(),
65 }
66 }
67
68 pub fn parse_query_string(query: &str) -> Self {
72 let mut q = Query {
73 inner: HashMap::new(),
74 raw: query.to_string(),
75 };
76 for pair in query.split('&').filter(|p| !p.is_empty()) {
77 let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
78 q.inner
79 .insert(decode_component(key), decode_component(value));
80 }
81 q
82 }
83
84 pub fn get(&self, key: &str) -> Option<&str> {
85 self.inner.get(key).map(|s| s.as_str())
86 }
87
88 pub fn contains(&self, key: &str) -> bool {
89 self.inner.contains_key(key)
90 }
91
92 pub fn is_empty(&self) -> bool {
93 self.inner.is_empty()
94 }
95
96 pub fn parse<T: DeserializeOwned>(&self) -> Result<T> {
99 serde_urlencoded::from_str(&self.raw)
100 .map_err(|e| Error::bad_request(format!("Invalid query params: {}", e)))
101 }
102}
103
104fn decode_component(s: &str) -> String {
105 let s = s.replace('+', " ");
106 urlencoding::decode(&s).map(|c| c.into_owned()).unwrap_or(s)
107}
108
109impl Default for Query {
110 fn default() -> Self {
111 Self::new()
112 }
113}
114
115#[derive(Debug, Clone)]
117pub struct ClientCertificate(pub Vec<u8>);
118
119#[derive(Default)]
121pub(crate) struct StateMap {
122 values: HashMap<std::any::TypeId, Arc<dyn std::any::Any + Send + Sync>>,
123}
124
125impl StateMap {
126 pub(crate) fn insert<T: Send + Sync + 'static>(&mut self, value: T) {
127 self.values
128 .insert(std::any::TypeId::of::<T>(), Arc::new(value));
129 }
130
131 pub(crate) fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
132 self.values
133 .get(&std::any::TypeId::of::<T>())
134 .and_then(|v| v.downcast_ref::<T>())
135 }
136
137 pub(crate) fn get_arc<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
138 self.values
139 .get(&std::any::TypeId::of::<T>())
140 .and_then(|v| v.clone().downcast::<T>().ok())
141 }
142}
143
144pub struct Request {
146 pub method: http::Method,
147 pub uri: http::Uri,
148 pub headers: http::HeaderMap,
149 pub body: bytes::Bytes,
150 pub params: Params,
151 pub query: Query,
152 pub extensions: http::Extensions,
155 pub remote_addr: Option<std::net::SocketAddr>,
157 pub matched_path: Option<std::sync::Arc<str>>,
161 pub secure: bool,
164 pub(crate) state: Option<std::sync::Arc<StateMap>>,
165 pub(crate) shutdown: Option<crate::shutdown::Shutdown>,
166 cookies: OnceLock<Cookies>,
167}
168
169impl Request {
170 pub fn new(
171 method: http::Method,
172 uri: http::Uri,
173 headers: http::HeaderMap,
174 body: bytes::Bytes,
175 ) -> Self {
176 let query = uri
177 .query()
178 .map(Query::parse_query_string)
179 .unwrap_or_default();
180
181 Self {
182 method,
183 uri,
184 headers,
185 body,
186 params: Params::new(),
187 query,
188 extensions: http::Extensions::new(),
189 remote_addr: None,
190 matched_path: None,
191 secure: false,
192 state: None,
193 shutdown: None,
194 cookies: OnceLock::new(),
195 }
196 }
197
198 pub(crate) fn duplicate(&self) -> Request {
200 let mut copy = Request::new(
201 self.method.clone(),
202 self.uri.clone(),
203 self.headers.clone(),
204 self.body.clone(),
205 );
206 copy.params = self.params.clone();
207 copy.extensions = self.extensions.clone();
208 copy.remote_addr = self.remote_addr;
209 copy.matched_path = self.matched_path.clone();
210 copy.secure = self.secure;
211 copy.state = self.state.clone();
212 copy.shutdown = self.shutdown.clone();
213 copy
214 }
215
216 pub fn is_secure(&self) -> bool {
218 self.secure
219 }
220
221 pub fn csp_nonce(&self) -> Option<&str> {
225 self.extensions
226 .get::<crate::security_headers::CspNonce>()
227 .map(|n| n.0.as_str())
228 }
229
230 pub fn client_certificate(&self) -> Option<&[u8]> {
236 self.extensions
237 .get::<ClientCertificate>()
238 .map(|c| c.0.as_slice())
239 }
240
241 pub fn state<T: Send + Sync + 'static>(&self) -> Result<&T> {
246 self.try_state().ok_or_else(|| {
247 Error::internal(format!(
248 "State of type {} is not registered",
249 std::any::type_name::<T>()
250 ))
251 })
252 }
253
254 pub fn shutdown_signal(&self) -> crate::shutdown::Shutdown {
259 self.shutdown
260 .clone()
261 .unwrap_or_else(crate::shutdown::Shutdown::never)
262 }
263
264 pub fn state_arc<T: Send + Sync + 'static>(&self) -> Result<Arc<T>> {
268 self.state
269 .as_ref()
270 .and_then(|s| s.get_arc::<T>())
271 .ok_or_else(|| {
272 Error::internal(format!(
273 "State of type {} is not registered",
274 std::any::type_name::<T>()
275 ))
276 })
277 }
278
279 pub fn try_state<T: Send + Sync + 'static>(&self) -> Option<&T> {
281 self.state.as_ref()?.get::<T>()
282 }
283
284 pub fn cookies(&self) -> &Cookies {
286 self.cookies.get_or_init(|| {
287 if let Some(cookie_header) = self.headers.get("cookie") {
288 if let Ok(cookie_str) = cookie_header.to_str() {
289 Cookies::parse(cookie_str)
290 } else {
291 Cookies::new()
292 }
293 } else {
294 Cookies::new()
295 }
296 })
297 }
298
299 pub fn form<T: DeserializeOwned>(&self) -> Result<T> {
304 self.require_form_content_type()?;
305 serde_urlencoded::from_bytes(&self.body)
306 .map_err(|e| Error::bad_request(format!("Invalid form data: {}", e)))
307 }
308
309 pub fn form_data(&self) -> Result<Query> {
311 self.require_form_content_type()?;
312 let text = std::str::from_utf8(&self.body)
313 .map_err(|_| Error::bad_request("Form data is not valid UTF-8"))?;
314 Ok(Query::parse_query_string(text))
315 }
316
317 fn require_form_content_type(&self) -> Result<()> {
318 let is_form = self
319 .headers
320 .get(http::header::CONTENT_TYPE)
321 .and_then(|v| v.to_str().ok())
322 .map(|v| {
323 v.split(';')
324 .next()
325 .unwrap_or("")
326 .trim()
327 .eq_ignore_ascii_case("application/x-www-form-urlencoded")
328 })
329 .unwrap_or(false);
330 if is_form {
331 Ok(())
332 } else {
333 Err(Error::custom(
334 415,
335 "Expected content-type application/x-www-form-urlencoded",
336 ))
337 }
338 }
339
340 pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
342 serde_json::from_slice(&self.body)
343 .map_err(|e| Error::bad_request(format!("Invalid JSON: {}", e)))
344 }
345}
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350
351 fn form_request(content_type: Option<&str>, body: &'static str) -> Request {
352 let mut headers = http::HeaderMap::new();
353 if let Some(ct) = content_type {
354 headers.insert(http::header::CONTENT_TYPE, ct.parse().unwrap());
355 }
356 Request::new(
357 http::Method::POST,
358 "/".parse().unwrap(),
359 headers,
360 bytes::Bytes::from_static(body.as_bytes()),
361 )
362 }
363
364 #[derive(Debug, serde::Deserialize, PartialEq)]
365 struct Signup {
366 name: String,
367 age: u8,
368 newsletter: Option<bool>,
369 }
370
371 #[test]
372 fn params_parse_typed_values() {
373 let mut p = Params::new();
374 p.insert("id".into(), "42".into());
375 p.insert("name".into(), "x".into());
376 assert_eq!(p.parse::<u64>("id").unwrap(), 42);
377 assert_eq!(p.parse::<String>("name").unwrap(), "x");
378 let bad = p.parse::<u64>("name").unwrap_err();
379 assert_eq!(bad.status_code(), 400);
380 assert_eq!(bad.message(), "Invalid path parameter 'name'");
381 assert_eq!(p.parse::<u64>("missing").unwrap_err().status_code(), 400);
382 assert!(p.parse::<u8>("id").is_ok());
383 p.insert("big".into(), "300".into());
384 assert!(p.parse::<u8>("big").is_err());
385 }
386
387 #[test]
388 fn query_decodes_keys_values_and_plus() {
389 let q = Query::parse_query_string("q=rust+web&na%20me=a%26b&flag&&x=1");
390 assert_eq!(q.get("q"), Some("rust web"));
391 assert_eq!(q.get("na me"), Some("a&b"));
392 assert_eq!(q.get("flag"), Some(""));
393 assert!(q.contains("x") && !q.is_empty());
394 }
395
396 #[test]
397 fn query_parse_converts_types() {
398 let q = Query::parse_query_string("name=Ann&age=31&newsletter=true");
399 assert_eq!(
400 q.parse::<Signup>().unwrap(),
401 Signup {
402 name: "Ann".into(),
403 age: 31,
404 newsletter: Some(true)
405 }
406 );
407 let bad = Query::parse_query_string("name=Ann&age=old");
408 assert_eq!(bad.parse::<Signup>().unwrap_err().status_code(), 400);
409 }
410
411 #[test]
412 fn form_typed_and_untyped() {
413 let req = form_request(
414 Some("application/x-www-form-urlencoded; charset=UTF-8"),
415 "name=Ann+Lee&age=31",
416 );
417 let signup: Signup = req.form().unwrap();
418 assert_eq!(
419 signup,
420 Signup {
421 name: "Ann Lee".into(),
422 age: 31,
423 newsletter: None
424 }
425 );
426 assert_eq!(req.form_data().unwrap().get("name"), Some("Ann Lee"));
427 }
428
429 #[test]
430 fn form_rejects_wrong_content_type_and_bad_values() {
431 let json = form_request(Some("application/json"), "name=Ann&age=1");
432 assert_eq!(json.form::<Signup>().unwrap_err().status_code(), 415);
433 let none = form_request(None, "name=Ann&age=1");
434 assert_eq!(none.form_data().unwrap_err().status_code(), 415);
435
436 let bad = form_request(
437 Some("application/x-www-form-urlencoded"),
438 "name=Ann&age=300",
439 );
440 assert_eq!(bad.form::<Signup>().unwrap_err().status_code(), 400);
441 }
442}