1use crate::cookie;
2use crate::headers::Headers;
3use crate::method::Method;
4use crate::url;
5use rustlavel_core::{Config, Context, Json};
6use std::any::{Any, TypeId};
7use std::collections::{BTreeMap, HashMap};
8use std::net::SocketAddr;
9
10pub struct Request {
12 pub(crate) method: Method,
13 pub(crate) target: String,
14 pub(crate) path: String,
15 pub(crate) query: Vec<(String, String)>,
16 pub(crate) headers: Headers,
17 pub(crate) body: Vec<u8>,
18 pub(crate) params: BTreeMap<String, String>,
19 pub(crate) context: Context,
20 pub(crate) peer: Option<SocketAddr>,
21 pub(crate) route: Option<String>,
22 extensions: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
24 parsed_body: Option<ParsedBody>,
26}
27
28enum ParsedBody {
29 Json(Json),
30 Form(Vec<(String, String)>),
31 None,
32}
33
34impl Request {
35 pub fn new(method: Method, target: impl Into<String>) -> Self {
38 let target = target.into();
39 let (path, query) = url::split_target(&target);
40 Request {
41 method,
42 path: path.to_string(),
43 query: url::parse_query(query),
44 target,
45 headers: Headers::new(),
46 body: Vec::new(),
47 params: BTreeMap::new(),
48 context: Context::default(),
49 peer: None,
50 route: None,
51 extensions: HashMap::new(),
52 parsed_body: None,
53 }
54 }
55
56 pub fn method(&self) -> Method {
57 self.method
58 }
59
60 pub fn path(&self) -> &str {
62 &self.path
63 }
64
65 pub fn target(&self) -> &str {
67 &self.target
68 }
69
70 pub fn route(&self) -> Option<&str> {
73 self.route.as_deref()
74 }
75
76 pub fn headers(&self) -> &Headers {
77 &self.headers
78 }
79
80 pub fn headers_mut(&mut self) -> &mut Headers {
81 &mut self.headers
82 }
83
84 pub fn header(&self, name: &str) -> Option<&str> {
85 self.headers.get(name)
86 }
87
88 pub fn body(&self) -> &[u8] {
89 &self.body
90 }
91
92 pub fn body_string(&self) -> String {
93 String::from_utf8_lossy(&self.body).into_owned()
94 }
95
96 pub fn context(&self) -> &Context {
97 &self.context
98 }
99
100 pub fn config(&self) -> &Config {
101 self.context.config()
102 }
103
104 pub fn state<T: Send + Sync + 'static>(&self) -> Option<&T> {
106 self.context.state::<T>()
107 }
108
109 pub fn peer_addr(&self) -> Option<SocketAddr> {
110 self.peer
111 }
112
113 pub fn ip(&self) -> Option<String> {
127 if let Some(forwarded) = self.extension::<crate::trusted_proxies::Forwarded>()
128 && let Some(ip) = &forwarded.ip
129 {
130 return Some(ip.clone());
131 }
132 self.peer.map(|addr| addr.ip().to_string())
133 }
134
135 pub fn scheme(&self) -> &str {
142 match self.extension::<crate::trusted_proxies::Forwarded>().and_then(|f| f.scheme.as_deref())
143 {
144 Some(scheme) => scheme,
145 None => "http",
146 }
147 }
148
149 pub fn is_secure(&self) -> bool {
150 self.scheme() == "https"
151 }
152
153 pub fn forwarded_host(&self) -> Option<&str> {
155 self.extension::<crate::trusted_proxies::Forwarded>()?.host.as_deref()
156 }
157
158 pub fn forwarded_port(&self) -> Option<u16> {
160 self.extension::<crate::trusted_proxies::Forwarded>()?.port
161 }
162
163 pub fn param(&self, name: &str) -> Option<&str> {
166 self.params.get(name).map(String::as_str)
167 }
168
169 pub fn param_as<T: std::str::FromStr>(&self, name: &str) -> Option<T> {
172 self.param(name)?.parse().ok()
173 }
174
175 pub fn params(&self) -> &BTreeMap<String, String> {
176 &self.params
177 }
178
179 pub fn query(&self, name: &str) -> Option<&str> {
180 self.query.iter().find(|(key, _)| key == name).map(|(_, value)| value.as_str())
181 }
182
183 pub fn query_all(&self, name: &str) -> Vec<&str> {
185 self.query
186 .iter()
187 .filter(|(key, _)| key == name)
188 .map(|(_, value)| value.as_str())
189 .collect()
190 }
191
192 pub fn query_pairs(&self) -> &[(String, String)] {
193 &self.query
194 }
195
196 pub fn content_type(&self) -> Option<&str> {
197 self.headers.content_type()
198 }
199
200 pub fn is_json(&self) -> bool {
201 self.content_type().is_some_and(|ct| ct.ends_with("json"))
202 }
203
204 pub fn wants_json(&self) -> bool {
206 self.is_json()
207 || self.headers.get("accept").is_some_and(|a| a.contains("application/json"))
208 || self.headers.get("x-requested-with").is_some_and(|x| x == "XMLHttpRequest")
209 }
210
211 pub fn json(&mut self) -> Option<&Json> {
213 self.parse_body();
214 match self.parsed_body.as_ref()? {
215 ParsedBody::Json(value) => Some(value),
216 _ => None,
217 }
218 }
219
220 pub fn input(&mut self, name: &str) -> Option<String> {
223 self.parse_body();
224 match self.parsed_body.as_ref() {
225 Some(ParsedBody::Json(value)) => {
226 if let Some(found) = value.get(name) {
227 return Some(match found {
228 Json::String(s) => s.clone(),
229 Json::Null => String::new(),
230 other => other.to_string(),
231 });
232 }
233 }
234 Some(ParsedBody::Form(pairs)) => {
235 if let Some((_, value)) = pairs.iter().find(|(key, _)| key == name) {
236 return Some(value.clone());
237 }
238 }
239 _ => {}
240 }
241 self.query(name).map(str::to_string)
242 }
243
244 pub fn inputs(&mut self, name: &str) -> Vec<String> {
257 let bare = name.strip_suffix("[]").unwrap_or(name).to_string();
258 let bracketed = format!("{bare}[]");
259
260 let from_query: Vec<String> = self
261 .query_pairs()
262 .iter()
263 .filter(|(key, _)| *key == bare || *key == bracketed)
264 .map(|(_, value)| value.clone())
265 .collect();
266
267 let mut values = from_query;
268 values.extend(
269 self.form()
270 .iter()
271 .filter(|(key, _)| *key == bare || *key == bracketed)
272 .map(|(_, value)| value.clone()),
273 );
274 values
275 }
276
277 pub fn form(&mut self) -> &[(String, String)] {
278 self.parse_body();
279 match self.parsed_body.as_ref() {
280 Some(ParsedBody::Form(pairs)) => pairs,
281 _ => &[],
282 }
283 }
284
285 fn parse_body(&mut self) {
286 if self.parsed_body.is_some() {
287 return;
288 }
289 let parsed = match self.headers.content_type() {
290 _ if self.body.is_empty() => ParsedBody::None,
291 Some(ct) if ct.ends_with("json") => match std::str::from_utf8(&self.body) {
292 Ok(text) => Json::parse(text).map_or(ParsedBody::None, ParsedBody::Json),
293 Err(_) => ParsedBody::None,
294 },
295 Some("application/x-www-form-urlencoded") => {
296 ParsedBody::Form(url::parse_query(&String::from_utf8_lossy(&self.body)))
297 }
298 _ => ParsedBody::None,
299 };
300 self.parsed_body = Some(parsed);
301 }
302
303 pub fn cookies(&self) -> BTreeMap<String, String> {
304 self.headers.get("cookie").map(cookie::parse_header).unwrap_or_default()
305 }
306
307 pub fn cookie(&self, name: &str) -> Option<String> {
308 self.cookies().remove(name)
309 }
310
311 pub fn extend<T: Send + Sync + 'static>(&mut self, value: T) {
313 self.extensions.insert(TypeId::of::<T>(), Box::new(value));
314 }
315
316 pub fn api_version(&self) -> Option<&str> {
320 self.extension::<crate::versioning::ApiVersion>().map(|v| v.0.as_str())
321 }
322
323 pub fn request_id(&self) -> Option<&str> {
326 self.extension::<crate::request_id::Assigned>().map(|id| id.0.as_str())
327 }
328
329 pub fn extension<T: Send + Sync + 'static>(&self) -> Option<&T> {
331 self.extensions.get(&TypeId::of::<T>()).and_then(|value| value.downcast_ref::<T>())
332 }
333
334 pub fn with_peer(mut self, peer: SocketAddr) -> Self {
338 self.peer = Some(peer);
339 self
340 }
341
342 pub fn with_header(mut self, name: &str, value: impl Into<String>) -> Self {
343 self.headers.set(name, value);
344 self
345 }
346
347 pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
348 self.body = body.into();
349 self.parsed_body = None;
350 self
351 }
352
353 pub fn with_json(self, value: Json) -> Self {
354 self.with_header("content-type", "application/json").with_body(value.to_string())
355 }
356
357 pub fn with_form(self, fields: &[(&str, &str)]) -> Self {
358 let encoded = fields
359 .iter()
360 .map(|(key, value)| format!("{}={}", url::encode(key), url::encode(value)))
361 .collect::<Vec<_>>()
362 .join("&");
363 self.with_header("content-type", "application/x-www-form-urlencoded").with_body(encoded)
364 }
365
366 pub fn with_context(mut self, context: Context) -> Self {
367 self.context = context;
368 self
369 }
370
371 pub(crate) fn set_params(&mut self, params: BTreeMap<String, String>) {
372 self.params = params;
373 }
374}
375
376impl std::fmt::Debug for Request {
377 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
378 f.debug_struct("Request")
379 .field("method", &self.method)
380 .field("target", &self.target)
381 .field("headers", &self.headers)
382 .field("body_len", &self.body.len())
383 .finish()
384 }
385}
386
387#[cfg(test)]
388mod tests {
389 #[test]
390 fn inputs_collects_every_value_under_one_name() {
391 let mut request = Request::new(Method::Post, "/roles?scope=a&scope=b")
392 .with_body(b"roles[]=admin&roles[]=editor&name=Ada".to_vec())
393 .with_header("content-type", "application/x-www-form-urlencoded");
394
395 assert_eq!(request.inputs("roles"), vec!["admin", "editor"]);
398 assert_eq!(request.inputs("roles[]"), vec!["admin", "editor"]);
399 assert_eq!(request.inputs("name"), vec!["Ada"]);
400 assert!(request.inputs("missing").is_empty());
401 assert_eq!(request.inputs("scope"), vec!["a", "b"]);
403 }
404
405 use super::*;
406
407 #[test]
408 fn splits_path_and_query() {
409 let request = Request::new(Method::Get, "/users?page=2&tag=a&tag=b");
410
411 assert_eq!(request.path(), "/users");
412 assert_eq!(request.query("page"), Some("2"));
413 assert_eq!(request.query_all("tag"), ["a", "b"]);
414 assert_eq!(request.query("missing"), None);
415 }
416
417 #[test]
418 fn input_prefers_the_body_over_the_query() {
419 let mut request = Request::new(Method::Post, "/users?name=from-query")
420 .with_json(Json::object([("name", "from-body".into())]));
421
422 assert_eq!(request.input("name").as_deref(), Some("from-body"));
423 assert_eq!(request.input("missing"), None);
425 }
426
427 #[test]
428 fn reads_urlencoded_form_bodies() {
429 let mut request =
430 Request::new(Method::Post, "/login").with_form(&[("email", "a@b.com"), ("password", "s e c")]);
431
432 assert_eq!(request.input("email").as_deref(), Some("a@b.com"));
433 assert_eq!(request.input("password").as_deref(), Some("s e c"));
434 assert_eq!(request.form().len(), 2);
435 }
436
437 #[test]
438 fn parses_cookies_from_the_header() {
439 let request = Request::new(Method::Get, "/").with_header("cookie", "session=abc; theme=dark");
440
441 assert_eq!(request.cookie("session").as_deref(), Some("abc"));
442 assert_eq!(request.cookies().len(), 2);
443 }
444
445 #[test]
446 fn extensions_round_trip_through_middleware() {
447 struct User(&'static str);
448 let mut request = Request::new(Method::Get, "/");
449 request.extend(User("ada"));
450
451 assert_eq!(request.extension::<User>().unwrap().0, "ada");
452 }
453
454 #[test]
455 fn a_forwarded_header_alone_does_not_decide_the_client_address() {
456 let request = Request::new(Method::Get, "/")
461 .with_peer("198.51.100.7:44321".parse().unwrap())
462 .with_header("x-forwarded-for", "203.0.113.9, 10.0.0.1");
463 assert_eq!(request.ip().as_deref(), Some("198.51.100.7"));
464 assert_eq!(request.scheme(), "http");
465 assert!(!request.is_secure());
466 }
467
468 #[test]
469 fn detects_clients_that_want_json() {
470 let api = Request::new(Method::Get, "/").with_header("accept", "application/json");
471 let browser = Request::new(Method::Get, "/").with_header("accept", "text/html");
472
473 assert!(api.wants_json());
474 assert!(!browser.wants_json());
475 }
476}