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 form(&mut self) -> &[(String, String)] {
246 self.parse_body();
247 match self.parsed_body.as_ref() {
248 Some(ParsedBody::Form(pairs)) => pairs,
249 _ => &[],
250 }
251 }
252
253 fn parse_body(&mut self) {
254 if self.parsed_body.is_some() {
255 return;
256 }
257 let parsed = match self.headers.content_type() {
258 _ if self.body.is_empty() => ParsedBody::None,
259 Some(ct) if ct.ends_with("json") => match std::str::from_utf8(&self.body) {
260 Ok(text) => Json::parse(text).map_or(ParsedBody::None, ParsedBody::Json),
261 Err(_) => ParsedBody::None,
262 },
263 Some("application/x-www-form-urlencoded") => {
264 ParsedBody::Form(url::parse_query(&String::from_utf8_lossy(&self.body)))
265 }
266 _ => ParsedBody::None,
267 };
268 self.parsed_body = Some(parsed);
269 }
270
271 pub fn cookies(&self) -> BTreeMap<String, String> {
272 self.headers.get("cookie").map(cookie::parse_header).unwrap_or_default()
273 }
274
275 pub fn cookie(&self, name: &str) -> Option<String> {
276 self.cookies().remove(name)
277 }
278
279 pub fn extend<T: Send + Sync + 'static>(&mut self, value: T) {
281 self.extensions.insert(TypeId::of::<T>(), Box::new(value));
282 }
283
284 pub fn api_version(&self) -> Option<&str> {
288 self.extension::<crate::versioning::ApiVersion>().map(|v| v.0.as_str())
289 }
290
291 pub fn request_id(&self) -> Option<&str> {
294 self.extension::<crate::request_id::Assigned>().map(|id| id.0.as_str())
295 }
296
297 pub fn extension<T: Send + Sync + 'static>(&self) -> Option<&T> {
299 self.extensions.get(&TypeId::of::<T>()).and_then(|value| value.downcast_ref::<T>())
300 }
301
302 pub fn with_peer(mut self, peer: SocketAddr) -> Self {
306 self.peer = Some(peer);
307 self
308 }
309
310 pub fn with_header(mut self, name: &str, value: impl Into<String>) -> Self {
311 self.headers.set(name, value);
312 self
313 }
314
315 pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
316 self.body = body.into();
317 self.parsed_body = None;
318 self
319 }
320
321 pub fn with_json(self, value: Json) -> Self {
322 self.with_header("content-type", "application/json").with_body(value.to_string())
323 }
324
325 pub fn with_form(self, fields: &[(&str, &str)]) -> Self {
326 let encoded = fields
327 .iter()
328 .map(|(key, value)| format!("{}={}", url::encode(key), url::encode(value)))
329 .collect::<Vec<_>>()
330 .join("&");
331 self.with_header("content-type", "application/x-www-form-urlencoded").with_body(encoded)
332 }
333
334 pub fn with_context(mut self, context: Context) -> Self {
335 self.context = context;
336 self
337 }
338
339 pub(crate) fn set_params(&mut self, params: BTreeMap<String, String>) {
340 self.params = params;
341 }
342}
343
344impl std::fmt::Debug for Request {
345 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346 f.debug_struct("Request")
347 .field("method", &self.method)
348 .field("target", &self.target)
349 .field("headers", &self.headers)
350 .field("body_len", &self.body.len())
351 .finish()
352 }
353}
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358
359 #[test]
360 fn splits_path_and_query() {
361 let request = Request::new(Method::Get, "/users?page=2&tag=a&tag=b");
362
363 assert_eq!(request.path(), "/users");
364 assert_eq!(request.query("page"), Some("2"));
365 assert_eq!(request.query_all("tag"), ["a", "b"]);
366 assert_eq!(request.query("missing"), None);
367 }
368
369 #[test]
370 fn input_prefers_the_body_over_the_query() {
371 let mut request = Request::new(Method::Post, "/users?name=from-query")
372 .with_json(Json::object([("name", "from-body".into())]));
373
374 assert_eq!(request.input("name").as_deref(), Some("from-body"));
375 assert_eq!(request.input("missing"), None);
377 }
378
379 #[test]
380 fn reads_urlencoded_form_bodies() {
381 let mut request =
382 Request::new(Method::Post, "/login").with_form(&[("email", "a@b.com"), ("password", "s e c")]);
383
384 assert_eq!(request.input("email").as_deref(), Some("a@b.com"));
385 assert_eq!(request.input("password").as_deref(), Some("s e c"));
386 assert_eq!(request.form().len(), 2);
387 }
388
389 #[test]
390 fn parses_cookies_from_the_header() {
391 let request = Request::new(Method::Get, "/").with_header("cookie", "session=abc; theme=dark");
392
393 assert_eq!(request.cookie("session").as_deref(), Some("abc"));
394 assert_eq!(request.cookies().len(), 2);
395 }
396
397 #[test]
398 fn extensions_round_trip_through_middleware() {
399 struct User(&'static str);
400 let mut request = Request::new(Method::Get, "/");
401 request.extend(User("ada"));
402
403 assert_eq!(request.extension::<User>().unwrap().0, "ada");
404 }
405
406 #[test]
407 fn a_forwarded_header_alone_does_not_decide_the_client_address() {
408 let request = Request::new(Method::Get, "/")
413 .with_peer("198.51.100.7:44321".parse().unwrap())
414 .with_header("x-forwarded-for", "203.0.113.9, 10.0.0.1");
415 assert_eq!(request.ip().as_deref(), Some("198.51.100.7"));
416 assert_eq!(request.scheme(), "http");
417 assert!(!request.is_secure());
418 }
419
420 #[test]
421 fn detects_clients_that_want_json() {
422 let api = Request::new(Method::Get, "/").with_header("accept", "application/json");
423 let browser = Request::new(Method::Get, "/").with_header("accept", "text/html");
424
425 assert!(api.wants_json());
426 assert!(!browser.wants_json());
427 }
428}