Skip to main content

rainier_http/
request.rs

1//! The incoming [`Request`].
2//!
3//! One object carrying the
4//! HTTP message *and* the conveniences an application actually reaches for —
5//! `input()`, `file()`, `cookie()`, `bearer_token()`, `expects_json()`.
6//!
7//! Parsing is **lazy but synchronous**. The body arrives already buffered, and
8//! the query string, cookies and body are each parsed on first access and
9//! cached in a `OnceLock`. A request that only reads a header never runs the
10//! form parser; a request that reads `input()` twice runs it once.
11
12use std::collections::HashMap;
13use std::sync::OnceLock;
14
15use bytes::Bytes;
16use http::{HeaderMap, Method, Uri, Version};
17use rainier_support::{Error, Extensions, Result};
18use serde::de::DeserializeOwned;
19use serde_json::Value;
20
21use crate::cookie::parse_cookie_header;
22use crate::input;
23use crate::upload::{self, Multipart, UploadedFile};
24
25/// The client's address, put into the request's extensions by the server.
26///
27/// A newtype rather than a bare `SocketAddr` so it cannot collide with another
28/// address an application stores in the same type-keyed bag.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct ClientIp(pub std::net::IpAddr);
31
32/// How a request body was interpreted.
33#[derive(Debug)]
34enum ParsedBody {
35    /// `application/json`, parsed.
36    Json(Value),
37    /// `application/x-www-form-urlencoded`, lifted into a JSON tree.
38    Form(Value),
39    /// `multipart/form-data`, split into fields and files.
40    Multipart(Box<Multipart>),
41    /// No body, an unrecognised content type, or a body that failed to parse.
42    /// Failures land here rather than erroring, because a handler that never
43    /// looks at the body should not care that it was malformed — the error
44    /// surfaces from [`Request::json`], which is where it can be reported.
45    Opaque,
46}
47
48/// An inbound HTTP request.
49#[derive(Debug)]
50pub struct Request {
51    method: Method,
52    uri: Uri,
53    version: Version,
54    headers: HeaderMap,
55    body: Bytes,
56    extensions: Extensions,
57    route_params: HashMap<String, String>,
58    /// Set by input-rewriting middleware (`TrimStrings`,
59    /// `ConvertEmptyStringsToNull`) and by `merge`. When present it *replaces*
60    /// the query-plus-body view entirely rather than layering over it — it was
61    /// derived from that view, so consulting the originals underneath it would
62    /// resurrect exactly the values the rewrite removed.
63    input_override: Option<Value>,
64
65    query: OnceLock<Value>,
66    parsed_body: OnceLock<ParsedBody>,
67    cookies: OnceLock<HashMap<String, String>>,
68}
69
70impl Request {
71    /// Build a request from its parts. The server calls this; tests should
72    /// prefer [`Request::builder`].
73    pub fn new(method: Method, uri: Uri, headers: HeaderMap, body: Bytes) -> Self {
74        Self {
75            method,
76            uri,
77            version: Version::HTTP_11,
78            headers,
79            body,
80            extensions: Extensions::new(),
81            route_params: HashMap::new(),
82            input_override: None,
83            query: OnceLock::new(),
84            parsed_body: OnceLock::new(),
85            cookies: OnceLock::new(),
86        }
87    }
88
89    /// A fluent builder, mainly for tests.
90    pub fn builder() -> RequestBuilder {
91        RequestBuilder::new()
92    }
93
94    /// Adopt an `http::Request` whose body has already been buffered.
95    pub fn from_http(request: http::Request<Bytes>) -> Self {
96        let (parts, body) = request.into_parts();
97        let mut request = Self::new(parts.method, parts.uri, parts.headers, body);
98        request.version = parts.version;
99        request
100    }
101
102    // --- the message ------------------------------------------------------
103
104    /// The HTTP method.
105    pub fn method(&self) -> &Method {
106        &self.method
107    }
108
109    /// The full request URI.
110    pub fn uri(&self) -> &Uri {
111        &self.uri
112    }
113
114    /// The path, without the query string. Always begins with `/`.
115    pub fn path(&self) -> &str {
116        self.uri.path()
117    }
118
119    /// The raw query string, without the `?`.
120    pub fn query_string(&self) -> &str {
121        self.uri.query().unwrap_or("")
122    }
123
124    /// The HTTP version.
125    pub fn version(&self) -> Version {
126        self.version
127    }
128
129    /// Every header.
130    pub fn headers(&self) -> &HeaderMap {
131        &self.headers
132    }
133
134    /// Mutable access to the headers — for middleware that normalises them.
135    pub fn headers_mut(&mut self) -> &mut HeaderMap {
136        &mut self.headers
137    }
138
139    /// One header as a string, or `None` if absent or not valid UTF-8.
140    pub fn header(&self, name: &str) -> Option<&str> {
141        self.headers.get(name)?.to_str().ok()
142    }
143
144    /// Replace the method.
145    ///
146    /// For the one middleware that legitimately needs it: turning a browser
147    /// form's `POST` with `_method=DELETE` into a real `DELETE` before routing
148    /// sees it. See
149    /// [`MethodOverride`](https://docs.rs/rainier-middleware) — and note that
150    /// it must run **before** the router, or the route has already been chosen
151    /// for the old method.
152    pub fn set_method(&mut self, method: Method) {
153        self.method = method;
154    }
155
156    /// Whether the method is `method`.
157    pub fn is_method(&self, method: &Method) -> bool {
158        self.method == method
159    }
160
161    /// The raw body bytes.
162    pub fn body(&self) -> &Bytes {
163        &self.body
164    }
165
166    /// The body as UTF-8, lossily.
167    pub fn body_string(&self) -> String {
168        String::from_utf8_lossy(&self.body).into_owned()
169    }
170
171    /// The `Content-Type` header, lowercased and without parameters.
172    pub fn content_type(&self) -> Option<String> {
173        let raw = self.header("content-type")?;
174        let base = raw.split(';').next().unwrap_or(raw);
175        Some(base.trim().to_ascii_lowercase())
176    }
177
178    /// Whether the body claims to be JSON. Also true for `+json` suffixes such
179    /// as `application/ld+json`.
180    pub fn is_json(&self) -> bool {
181        self.content_type().is_some_and(|ct| ct == "application/json" || ct.ends_with("+json"))
182    }
183
184    /// Whether the client would rather have JSON back.
185    ///
186    /// True when it sent JSON, when it asked for JSON in `Accept`, or when it
187    /// looks like an XHR. This is what the exception handler consults to decide
188    /// between a JSON error body and an HTML error page.
189    pub fn expects_json(&self) -> bool {
190        if self.is_json() {
191            return true;
192        }
193        if self.header("x-requested-with").is_some_and(|v| v.eq_ignore_ascii_case("XMLHttpRequest"))
194        {
195            return true;
196        }
197        match self.header("accept") {
198            // `*/*` is what a plain browser navigation and curl both send, so
199            // it must not count as "wants JSON".
200            Some(accept) => accept.split(',').any(|part| {
201                let part = part.split(';').next().unwrap_or(part).trim();
202                part == "application/json" || part.ends_with("+json")
203            }),
204            None => false,
205        }
206    }
207
208    // --- input ------------------------------------------------------------
209
210    /// The query string parsed into a JSON tree.
211    pub fn query(&self) -> &Value {
212        self.query.get_or_init(|| input::parse_urlencoded(self.query_string().as_bytes()))
213    }
214
215    fn parsed_body(&self) -> &ParsedBody {
216        self.parsed_body.get_or_init(|| {
217            if self.body.is_empty() {
218                return ParsedBody::Opaque;
219            }
220            match self.content_type().as_deref() {
221                Some(ct) if ct == "application/json" || ct.ends_with("+json") => {
222                    match serde_json::from_slice(&self.body) {
223                        Ok(value) => ParsedBody::Json(value),
224                        Err(_) => ParsedBody::Opaque,
225                    }
226                }
227                Some("application/x-www-form-urlencoded") => {
228                    ParsedBody::Form(input::parse_urlencoded(&self.body))
229                }
230                Some("multipart/form-data") => {
231                    let boundary = self.header("content-type").and_then(upload::boundary_of);
232                    match boundary.and_then(|b| upload::parse(&self.body, &b).ok()) {
233                        Some(parsed) => ParsedBody::Multipart(Box::new(parsed)),
234                        None => ParsedBody::Opaque,
235                    }
236                }
237                _ => ParsedBody::Opaque,
238            }
239        })
240    }
241
242    /// The body's fields as a JSON tree — `{}` when there is no parseable body.
243    pub fn body_input(&self) -> &Value {
244        static EMPTY: OnceLock<Value> = OnceLock::new();
245        if let Some(overridden) = &self.input_override {
246            return overridden;
247        }
248        match self.parsed_body() {
249            ParsedBody::Json(value) => value,
250            ParsedBody::Form(value) => value,
251            ParsedBody::Multipart(parsed) => &parsed.fields,
252            ParsedBody::Opaque => EMPTY.get_or_init(|| Value::Object(serde_json::Map::new())),
253        }
254    }
255
256    /// Every input: the query string with the body merged over it.
257    ///
258    /// Route parameters are **not** included — they are part
259    /// of the URL's shape rather than user input, and mixing them in would let
260    /// a query string shadow a route binding. Read them with
261    /// [`route_param`](Self::route_param).
262    pub fn all(&self) -> Value {
263        match &self.input_override {
264            Some(overridden) => overridden.clone(),
265            None => input::merge(self.query().clone(), self.body_input().clone()),
266        }
267    }
268
269    /// One input by dotted key, as a string. Body wins over query string.
270    pub fn input(&self, key: &str) -> Option<String> {
271        if let Some(overridden) = &self.input_override {
272            return input::lookup(overridden, key).and_then(input::scalar_to_string);
273        }
274        input::lookup(self.body_input(), key)
275            .or_else(|| input::lookup(self.query(), key))
276            .and_then(input::scalar_to_string)
277    }
278
279    /// Rewrite every input through `transform`.
280    ///
281    /// The seam input-normalising middleware works through: `TrimStrings` and
282    /// `ConvertEmptyStringsToNull` both take [`all`](Self::all), reshape it,
283    /// and hand it back. Later reads see only the rewritten values.
284    pub fn transform_input(&mut self, transform: impl FnOnce(Value) -> Value) {
285        self.input_override = Some(transform(self.all()));
286    }
287
288    /// Replace every input outright.
289    pub fn set_input(&mut self, value: Value) {
290        self.input_override = Some(value);
291    }
292
293    /// Merge extra values over the current inputs, for a middleware that
294    /// resolves something the handler should read as ordinary input.
295    pub fn merge_input(&mut self, extra: Value) {
296        self.transform_input(|current| input::merge(current, extra));
297    }
298
299    /// One input, or `default`.
300    pub fn input_or(&self, key: &str, default: impl Into<String>) -> String {
301        self.input(key).unwrap_or_else(|| default.into())
302    }
303
304    /// The raw JSON value at `key`, for non-scalar inputs.
305    pub fn input_value(&self, key: &str) -> Option<&Value> {
306        if let Some(overridden) = &self.input_override {
307            return input::lookup(overridden, key);
308        }
309        input::lookup(self.body_input(), key).or_else(|| input::lookup(self.query(), key))
310    }
311
312    /// Whether `key` is present at all (even if empty).
313    pub fn has(&self, key: &str) -> bool {
314        self.input_value(key).is_some()
315    }
316
317    /// Whether input-rewriting middleware has replaced the inputs.
318    pub fn input_was_rewritten(&self) -> bool {
319        self.input_override.is_some()
320    }
321
322    /// Whether `key` is present and not empty.
323    pub fn filled(&self, key: &str) -> bool {
324        match self.input_value(key) {
325            Some(Value::String(s)) => !s.trim().is_empty(),
326            Some(Value::Null) | None => false,
327            Some(Value::Array(items)) => !items.is_empty(),
328            Some(Value::Object(map)) => !map.is_empty(),
329            Some(_) => true,
330        }
331    }
332
333    /// Deserialise the JSON body into `T`.
334    ///
335    /// Fails with a 400 when the body is absent, is not JSON, or does not fit
336    /// `T` — unlike [`input`](Self::input), which shrugs at a bad body.
337    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
338        if self.body.is_empty() {
339            return Err(Error::bad_request("a JSON body is required but the request had none"));
340        }
341        if !self.is_json() {
342            return Err(Error::bad_request(format!(
343                "expected a JSON body but the Content-Type was `{}`",
344                self.content_type().unwrap_or_else(|| "(none)".into())
345            )));
346        }
347        serde_json::from_slice(&self.body)
348            .map_err(|e| Error::bad_request(format!("malformed JSON body: {e}")))
349    }
350
351    /// Deserialise the merged inputs into `T`.
352    ///
353    /// Every value from a form or query string is a string, so `T` should
354    /// either use string fields or `#[serde(deserialize_with = ..)]` coercions.
355    /// For typed coercion from forms, validate instead.
356    pub fn form<T: DeserializeOwned>(&self) -> Result<T> {
357        serde_json::from_value(self.all())
358            .map_err(|e| Error::bad_request(format!("could not read the request input: {e}")))
359    }
360
361    /// Deserialise the query string into `T`.
362    pub fn query_as<T: DeserializeOwned>(&self) -> Result<T> {
363        serde_json::from_value(self.query().clone())
364            .map_err(|e| Error::bad_request(format!("could not read the query string: {e}")))
365    }
366
367    // --- files -------------------------------------------------------------
368
369    /// Every file uploaded under `field`.
370    pub fn files(&self, field: &str) -> &[UploadedFile] {
371        match self.parsed_body() {
372            ParsedBody::Multipart(parsed) => {
373                parsed.files.get(field).map(Vec::as_slice).unwrap_or(&[])
374            }
375            _ => &[],
376        }
377    }
378
379    /// The first file uploaded under `field`.
380    pub fn file(&self, field: &str) -> Option<&UploadedFile> {
381        self.files(field).first()
382    }
383
384    /// Whether a non-empty file arrived under `field`.
385    pub fn has_file(&self, field: &str) -> bool {
386        self.file(field).is_some_and(|f| !f.is_empty())
387    }
388
389    // --- cookies -----------------------------------------------------------
390
391    /// Every cookie the client sent.
392    pub fn cookies(&self) -> &HashMap<String, String> {
393        self.cookies.get_or_init(|| match self.header("cookie") {
394            Some(header) => parse_cookie_header(header),
395            None => HashMap::new(),
396        })
397    }
398
399    /// One cookie's value.
400    pub fn cookie(&self, name: &str) -> Option<&str> {
401        self.cookies().get(name).map(String::as_str)
402    }
403
404    /// The `Authorization: Bearer …` token, if present.
405    pub fn bearer_token(&self) -> Option<&str> {
406        let header = self.header("authorization")?;
407        let (scheme, token) = header.split_once(' ')?;
408        scheme.eq_ignore_ascii_case("bearer").then(|| token.trim())
409    }
410
411    // --- route parameters --------------------------------------------------
412
413    /// A parameter captured by the matched route (`/posts/{post}`).
414    pub fn route_param(&self, name: &str) -> Option<&str> {
415        self.route_params.get(name).map(String::as_str)
416    }
417
418    /// Every captured route parameter.
419    pub fn route_params(&self) -> &HashMap<String, String> {
420        &self.route_params
421    }
422
423    /// Replace the captured route parameters. The router calls this on match.
424    pub fn set_route_params(&mut self, params: HashMap<String, String>) {
425        self.route_params = params;
426    }
427
428    // --- extensions --------------------------------------------------------
429
430    /// Per-request attributes, keyed by type: the authenticated user, the
431    /// matched route, a resolved model binding.
432    pub fn extensions(&self) -> &Extensions {
433        &self.extensions
434    }
435
436    /// Mutable per-request attributes.
437    pub fn extensions_mut(&mut self) -> &mut Extensions {
438        &mut self.extensions
439    }
440
441    /// Store a per-request attribute, returning `self` for chaining.
442    pub fn with_extension<T: Send + Sync + 'static>(mut self, value: T) -> Self {
443        self.extensions.insert(value);
444        self
445    }
446
447    /// Read a per-request attribute.
448    pub fn extension<T: Send + Sync + 'static>(&self) -> Option<&T> {
449        self.extensions.get::<T>()
450    }
451
452    /// The client's IP, if the server recorded one.
453    pub fn ip(&self) -> Option<std::net::IpAddr> {
454        self.extensions.get::<ClientIp>().map(|ip| ip.0)
455    }
456}
457
458/// A fluent [`Request`] builder.
459///
460/// ```
461/// # use rainier_http::Request;
462/// # use http::Method;
463/// let request = Request::builder()
464///     .method(Method::POST)
465///     .uri("/posts?draft=1")
466///     .json(&serde_json::json!({ "title": "Hello" }))
467///     .build();
468///
469/// assert_eq!(request.input("title").as_deref(), Some("Hello"));
470/// assert_eq!(request.input("draft").as_deref(), Some("1"));
471/// ```
472#[derive(Debug)]
473pub struct RequestBuilder {
474    method: Method,
475    uri: String,
476    headers: HeaderMap,
477    body: Bytes,
478    route_params: HashMap<String, String>,
479}
480
481impl Default for RequestBuilder {
482    fn default() -> Self {
483        Self::new()
484    }
485}
486
487impl RequestBuilder {
488    /// A `GET /` request with no headers or body.
489    pub fn new() -> Self {
490        Self {
491            method: Method::GET,
492            uri: "/".to_string(),
493            headers: HeaderMap::new(),
494            body: Bytes::new(),
495            route_params: HashMap::new(),
496        }
497    }
498
499    /// Set the method.
500    pub fn method(mut self, method: Method) -> Self {
501        self.method = method;
502        self
503    }
504
505    /// Set the URI (path and optional query string).
506    pub fn uri(mut self, uri: impl Into<String>) -> Self {
507        self.uri = uri.into();
508        self
509    }
510
511    /// Add a header. Ignored if the name or value is not a legal header.
512    pub fn header(mut self, name: &str, value: &str) -> Self {
513        if let (Ok(name), Ok(value)) =
514            (http::header::HeaderName::try_from(name), http::header::HeaderValue::from_str(value))
515        {
516            self.headers.insert(name, value);
517        }
518        self
519    }
520
521    /// Set a raw body.
522    pub fn body(mut self, body: impl Into<Bytes>) -> Self {
523        self.body = body.into();
524        self
525    }
526
527    /// Set a JSON body and the matching `Content-Type`.
528    pub fn json(self, value: &impl serde::Serialize) -> Self {
529        let encoded = serde_json::to_vec(value).unwrap_or_default();
530        self.header("content-type", "application/json").body(encoded)
531    }
532
533    /// Set a urlencoded form body and the matching `Content-Type`.
534    pub fn form(self, pairs: &[(&str, &str)]) -> Self {
535        let encoded: String =
536            form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish();
537        self.header("content-type", "application/x-www-form-urlencoded").body(encoded)
538    }
539
540    /// Pre-set a route parameter, as the router would after matching.
541    pub fn route_param(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
542        self.route_params.insert(name.into(), value.into());
543        self
544    }
545
546    /// Build the request.
547    pub fn build(self) -> Request {
548        let uri: Uri = self.uri.parse().unwrap_or_else(|_| Uri::from_static("/"));
549        let mut request = Request::new(self.method, uri, self.headers, self.body);
550        request.route_params = self.route_params;
551        request
552    }
553}
554
555#[cfg(test)]
556mod input_rewriting_tests {
557    use super::*;
558    use serde_json::json;
559
560    #[test]
561    fn transform_input_replaces_what_later_reads_see() {
562        let mut request = Request::builder().uri("/x?name=+ada+&age=36").build();
563        assert_eq!(request.input("name").as_deref(), Some(" ada "));
564
565        request.transform_input(|value| {
566            let mut object = value.as_object().cloned().unwrap_or_default();
567            if let Some(Value::String(name)) = object.get_mut("name") {
568                *name = name.trim().to_string();
569            }
570            Value::Object(object)
571        });
572
573        assert!(request.input_was_rewritten());
574        assert_eq!(request.input("name").as_deref(), Some("ada"));
575        assert_eq!(request.all(), json!({ "name": "ada", "age": "36" }));
576    }
577
578    #[test]
579    fn a_rewrite_is_not_undone_by_the_original_query_string() {
580        // Regression guard: if `input()` fell back to the query string after a
581        // rewrite, removing a value would be impossible.
582        let mut request = Request::builder().uri("/x?secret=leak").build();
583        request.set_input(json!({}));
584        assert_eq!(request.input("secret"), None);
585        assert!(!request.has("secret"));
586    }
587
588    #[test]
589    fn merge_input_layers_over_the_current_values() {
590        let mut request = Request::builder().uri("/x?a=1").build();
591        request.merge_input(json!({ "b": "2" }));
592        assert_eq!(request.all(), json!({ "a": "1", "b": "2" }));
593    }
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599    use serde_json::json;
600
601    #[test]
602    fn exposes_the_message_basics() {
603        let request = Request::builder().method(Method::POST).uri("/posts?page=2").build();
604        assert_eq!(request.method(), Method::POST);
605        assert_eq!(request.path(), "/posts");
606        assert_eq!(request.query_string(), "page=2");
607        assert!(request.is_method(&Method::POST));
608    }
609
610    #[test]
611    fn reads_query_string_input() {
612        let request = Request::builder().uri("/search?q=rust&tags[]=a&tags[]=b").build();
613        assert_eq!(request.input("q").as_deref(), Some("rust"));
614        assert_eq!(request.input_value("tags"), Some(&json!(["a", "b"])));
615    }
616
617    #[test]
618    fn reads_json_body_input() {
619        let request = Request::builder()
620            .method(Method::POST)
621            .json(&json!({ "title": "Hi", "meta": { "tag": "rust" } }))
622            .build();
623
624        assert_eq!(request.input("title").as_deref(), Some("Hi"));
625        assert_eq!(request.input("meta.tag").as_deref(), Some("rust"));
626        assert!(request.is_json());
627    }
628
629    #[test]
630    fn reads_form_body_input() {
631        let request = Request::builder()
632            .method(Method::POST)
633            .form(&[("title", "Hi"), ("body", "there")])
634            .build();
635        assert_eq!(request.input("title").as_deref(), Some("Hi"));
636        assert_eq!(request.input("body").as_deref(), Some("there"));
637    }
638
639    #[test]
640    fn the_body_wins_over_the_query_string() {
641        let request = Request::builder()
642            .method(Method::POST)
643            .uri("/x?name=query")
644            .json(&json!({ "name": "body" }))
645            .build();
646        assert_eq!(request.input("name").as_deref(), Some("body"));
647        assert_eq!(request.all(), json!({ "name": "body" }));
648    }
649
650    #[test]
651    fn all_merges_query_and_body() {
652        let request = Request::builder()
653            .method(Method::POST)
654            .uri("/x?page=2")
655            .json(&json!({ "name": "ada" }))
656            .build();
657        assert_eq!(request.all(), json!({ "page": "2", "name": "ada" }));
658    }
659
660    #[test]
661    fn route_params_stay_out_of_input() {
662        let request = Request::builder().uri("/posts/7").route_param("post", "7").build();
663        assert_eq!(request.route_param("post"), Some("7"));
664        assert!(!request.has("post"), "route params must not shadow or appear as input");
665    }
666
667    #[test]
668    fn has_and_filled_differ_on_blank_values() {
669        let request = Request::builder().uri("/x?a=&b=v&c[]=").build();
670        assert!(request.has("a"));
671        assert!(!request.filled("a"));
672        assert!(request.filled("b"));
673        assert!(!request.has("missing"));
674    }
675
676    #[test]
677    fn json_reports_why_it_failed() {
678        let empty = Request::builder().build();
679        assert!(empty.json::<Value>().unwrap_err().message().contains("had none"));
680
681        let wrong_type = Request::builder().body("hello").build();
682        assert!(wrong_type.json::<Value>().unwrap_err().message().contains("Content-Type"));
683
684        let malformed =
685            Request::builder().header("content-type", "application/json").body("{oops").build();
686        let err = malformed.json::<Value>().unwrap_err();
687        assert_eq!(err.status(), 400);
688        assert!(err.message().contains("malformed JSON"));
689    }
690
691    #[test]
692    fn a_malformed_body_does_not_break_unrelated_accessors() {
693        let request = Request::builder()
694            .header("content-type", "application/json")
695            .uri("/x?page=2")
696            .body("{oops")
697            .build();
698        // The handler never looks at the body; reading a query param must work.
699        assert_eq!(request.input("page").as_deref(), Some("2"));
700        assert_eq!(request.body_input(), &json!({}));
701    }
702
703    #[test]
704    fn detects_json_content_types_including_suffixes() {
705        let plain =
706            Request::builder().header("content-type", "application/json; charset=utf-8").build();
707        assert!(plain.is_json());
708        assert_eq!(plain.content_type().as_deref(), Some("application/json"));
709
710        let suffixed = Request::builder().header("content-type", "application/ld+json").build();
711        assert!(suffixed.is_json());
712
713        let html = Request::builder().header("content-type", "text/html").build();
714        assert!(!html.is_json());
715    }
716
717    #[test]
718    fn expects_json_reads_the_accept_header() {
719        let asked = Request::builder().header("accept", "application/json").build();
720        assert!(asked.expects_json());
721
722        let xhr = Request::builder().header("x-requested-with", "XMLHttpRequest").build();
723        assert!(xhr.expects_json());
724
725        let browser = Request::builder()
726            .header("accept", "text/html,application/xhtml+xml,*/*;q=0.8")
727            .build();
728        assert!(!browser.expects_json(), "`*/*` must not count as wanting JSON");
729
730        assert!(!Request::builder().build().expects_json());
731    }
732
733    #[test]
734    fn reads_cookies() {
735        let request = Request::builder().header("cookie", "session=abc; theme=dark").build();
736        assert_eq!(request.cookie("session"), Some("abc"));
737        assert_eq!(request.cookie("nope"), None);
738        assert_eq!(request.cookies().len(), 2);
739    }
740
741    #[test]
742    fn reads_a_bearer_token() {
743        let request = Request::builder().header("authorization", "Bearer tok_123").build();
744        assert_eq!(request.bearer_token(), Some("tok_123"));
745
746        // Case-insensitive scheme, per RFC 7235.
747        let lower = Request::builder().header("authorization", "bearer tok_123").build();
748        assert_eq!(lower.bearer_token(), Some("tok_123"));
749
750        let basic = Request::builder().header("authorization", "Basic abc").build();
751        assert_eq!(basic.bearer_token(), None);
752        assert_eq!(Request::builder().build().bearer_token(), None);
753    }
754
755    #[test]
756    fn extensions_carry_typed_attributes() {
757        #[derive(Debug, PartialEq)]
758        struct CurrentUser(u64);
759
760        let request = Request::builder().build().with_extension(CurrentUser(7));
761        assert_eq!(request.extension::<CurrentUser>(), Some(&CurrentUser(7)));
762        assert_eq!(request.extension::<ClientIp>(), None);
763    }
764
765    #[test]
766    fn deserialises_the_json_body_into_a_struct() {
767        #[derive(serde::Deserialize, PartialEq, Debug)]
768        struct NewPost {
769            title: String,
770            draft: bool,
771        }
772
773        let request = Request::builder()
774            .method(Method::POST)
775            .json(&json!({ "title": "Hi", "draft": true }))
776            .build();
777        assert_eq!(request.json::<NewPost>().unwrap(), NewPost { title: "Hi".into(), draft: true });
778    }
779
780    #[test]
781    fn parses_uploads_from_a_multipart_body() {
782        let boundary = "X";
783        let body = format!(
784            "--{boundary}\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nHi\r\n\
785             --{boundary}\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\nDATA\r\n\
786             --{boundary}--\r\n"
787        );
788        let request = Request::builder()
789            .method(Method::POST)
790            .header("content-type", &format!("multipart/form-data; boundary={boundary}"))
791            .body(body)
792            .build();
793
794        assert_eq!(request.input("title").as_deref(), Some("Hi"));
795        assert!(request.has_file("doc"));
796        assert_eq!(request.file("doc").unwrap().bytes().as_ref(), b"DATA");
797        assert!(!request.has_file("missing"));
798        assert!(request.files("missing").is_empty());
799    }
800
801    #[test]
802    fn parsing_is_cached_across_calls() {
803        let request = Request::builder().uri("/x?a=1").build();
804        let first = request.query() as *const Value;
805        let second = request.query() as *const Value;
806        assert_eq!(first, second, "the query string must be parsed once");
807    }
808
809    #[test]
810    fn adopts_an_http_request() {
811        let inner = http::Request::builder()
812            .method(Method::PUT)
813            .uri("/things/1")
814            .header("x-test", "yes")
815            .body(Bytes::from("payload"))
816            .unwrap();
817
818        let request = Request::from_http(inner);
819        assert_eq!(request.method(), Method::PUT);
820        assert_eq!(request.path(), "/things/1");
821        assert_eq!(request.header("x-test"), Some("yes"));
822        assert_eq!(request.body_string(), "payload");
823    }
824}