Skip to main content

ntex/web/types/
json.rs

1//! Json extractor/responder
2use std::task::{Context, Poll, ready};
3use std::{
4    fmt, future::Future, future::poll_fn, marker::PhantomData, mem, ops, pin::Pin, sync::Arc,
5};
6
7use serde::{Serialize, de::DeserializeOwned};
8
9use crate::http::header::CONTENT_LENGTH;
10use crate::http::{HttpMessage, Payload, Response, StatusCode, error::PayloadError};
11use crate::web::error::{JsonError, JsonPayloadError, WebResponseError};
12use crate::web::{FromRequest, HttpRequest, Responder, State};
13
14/// Json helper
15///
16/// Json can be used for two different purpose. First is for json response
17/// generation and second is for extracting typed information from request's
18/// payload.
19///
20/// To extract typed information from request's body, the type `T` must
21/// implement the `Deserialize` trait from *serde*.
22///
23/// [`JsonConfig`] allows to configure extraction
24/// process.
25///
26/// ## Example
27///
28/// ```rust
29/// use ntex::web;
30///
31/// #[derive(serde::Deserialize)]
32/// struct Info {
33///     username: String,
34/// }
35///
36/// /// deserialize `Info` from request's body
37/// async fn index(info: web::types::Json<Info>) -> String {
38///     format!("Welcome {}!", info.username)
39/// }
40///
41/// fn main() {
42///     let app = web::App::default().service(
43///        web::resource("/index.html").route(
44///            web::post().to(index))
45///     );
46/// }
47/// ```
48///
49/// The `Json` type allows you to respond with well-formed JSON data: simply
50/// return a value of type `Json<T>` where T is the type of a structure
51/// to serialize into *JSON*. The type `T` must implement the `Serialize`
52/// trait from *serde*.
53///
54/// ```rust
55/// use ntex::web;
56///
57/// #[derive(serde::Serialize)]
58/// struct MyObj {
59///     name: String,
60/// }
61///
62/// fn index(req: web::HttpRequest) -> Result<web::types::Json<MyObj>, std::io::Error> {
63///     Ok(web::types::Json(MyObj {
64///         name: req.match_info().get("name").unwrap().to_string(),
65///     }))
66/// }
67/// # fn main() {}
68/// ```
69pub struct Json<T>(pub T);
70
71impl<T> Json<T> {
72    /// Deconstruct to an inner value
73    pub fn into_inner(self) -> T {
74        self.0
75    }
76}
77
78impl<T> ops::Deref for Json<T> {
79    type Target = T;
80
81    fn deref(&self) -> &T {
82        &self.0
83    }
84}
85
86impl<T> ops::DerefMut for Json<T> {
87    fn deref_mut(&mut self) -> &mut T {
88        &mut self.0
89    }
90}
91
92impl<T> fmt::Debug for Json<T>
93where
94    T: fmt::Debug,
95{
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        f.debug_tuple("Json").field(&self.0).finish()
98    }
99}
100
101impl<T> fmt::Display for Json<T>
102where
103    T: fmt::Display,
104{
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        fmt::Display::fmt(&self.0, f)
107    }
108}
109
110impl<St, T: Serialize> Responder<St> for Json<T>
111where
112    St: State,
113    JsonError: WebResponseError<St, St::Error>,
114{
115    async fn respond_to(self, st: &St, _: &HttpRequest) -> Response {
116        let body = match crate::http::json::to_bytes(&self.0) {
117            Ok(body) => body,
118            Err(e) => return e.error_response(st),
119        };
120
121        Response::builder(StatusCode::OK)
122            .content_type("application/json")
123            .body(body)
124    }
125}
126
127/// Json extractor. Allow to extract typed information from request's
128/// payload.
129///
130/// To extract typed information from request's body, the type `T` must
131/// implement the `Deserialize` trait from *serde*.
132///
133/// [`JsonConfig`] allows to configure extraction
134/// process.
135///
136/// ## Example
137///
138/// ```rust
139/// use ntex::web;
140///
141/// #[derive(serde::Deserialize)]
142/// struct Info {
143///     username: String,
144/// }
145///
146/// /// deserialize `Info` from request's body
147/// async fn index(info: web::types::Json<Info>) -> String {
148///     format!("Welcome {}!", info.username)
149/// }
150///
151/// fn main() {
152///     let app = web::App::default().service(
153///         web::resource("/index.html").route(
154///            web::post().to(index))
155///     );
156/// }
157/// ```
158impl<St, T> FromRequest<St> for Json<T>
159where
160    St: State,
161    T: DeserializeOwned + 'static,
162{
163    type Error = JsonPayloadError;
164
165    // Checks run when the future is created, so it holds only the body reader
166    fn from_request(
167        _: &St,
168        req: &HttpRequest,
169        payload: &mut Payload,
170    ) -> impl Future<Output = Result<Self, Self::Error>> {
171        let (limit, ctype) = req
172            .app_value::<JsonConfig>()
173            .map_or((32768, None), |c| (c.limit, c.content_type.as_ref()));
174
175        let mut body = JsonBody::new(req, payload, ctype).limit(limit);
176        poll_fn(move |cx| match ready!(Pin::new(&mut body).poll(cx)) {
177            Err(e) => {
178                log::debug!(
179                    "Failed to deserialize Json from payload. \
180                     Request path: {}",
181                    req.path()
182                );
183                Poll::Ready(Err(e))
184            }
185            Ok(data) => Poll::Ready(Ok(Json(data))),
186        })
187    }
188}
189
190/// Json extractor configuration
191///
192/// Register it with [`WebAppConfig::set_value()`](crate::web::WebAppConfig::set_value)
193/// and [`App::with_config()`](crate::web::App::with_config). The extractor
194/// does not read the application state, so a config stored in
195/// [`AppState`](crate::web::AppState) has no effect.
196///
197/// ```rust
198/// use ntex::http::error;
199/// use ntex::web::{self, App, FromRequest, HttpResponse, WebAppConfig};
200///
201/// #[derive(serde::Deserialize)]
202/// struct Info {
203///     username: String,
204/// }
205///
206/// /// deserialize `Info` from request's body, max payload size is 4kb
207/// async fn index(info: web::types::Json<Info>) -> String {
208///     format!("Welcome {}!", info.username)
209/// }
210///
211/// fn main() {
212///     let cfg = WebAppConfig::new()
213///         .set_value(
214///             // change json extractor configuration
215///             web::types::JsonConfig::default()
216///                 .limit(4096)
217///                 .content_type(|mime| {  // <- accept JSON and text/plain content types
218///                     mime.subtype() == mime::JSON
219///                         || mime.suffix() == Some(mime::JSON)
220///                         || (mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN)
221///                 }));
222///
223///     let app = App::default()
224///         .with_config(cfg)
225///         .service(web::resource("/index.html")
226///             .route(web::post().to(index))
227///     );
228/// }
229/// ```
230#[derive(Clone)]
231pub struct JsonConfig {
232    limit: usize,
233    content_type: Option<Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
234}
235
236impl JsonConfig {
237    #[must_use]
238    /// Change max size of payload.
239    ///
240    /// By default max size is 32Kb
241    pub fn limit(mut self, limit: usize) -> Self {
242        self.limit = limit;
243        self
244    }
245
246    #[must_use]
247    /// Set predicate for allowed content types.
248    ///
249    /// By default, JSON content types (`*/json` and `*/*+json`) are accepted.
250    /// A predicate replaces this check: only content types for which it
251    /// returns `true` are accepted, so include the JSON types in the predicate
252    /// to keep accepting them. Requests without a valid `Content-Type` header
253    /// are always rejected.
254    pub fn content_type<F>(mut self, predicate: F) -> Self
255    where
256        F: Fn(mime::Mime) -> bool + Send + Sync + 'static,
257    {
258        self.content_type = Some(Arc::new(predicate));
259        self
260    }
261}
262
263impl Default for JsonConfig {
264    fn default() -> Self {
265        JsonConfig {
266            limit: 32768,
267            content_type: None,
268        }
269    }
270}
271
272impl fmt::Debug for JsonConfig {
273    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274        f.debug_struct("JsonConfig")
275            .field("limit", &self.limit)
276            .field(
277                "content_type",
278                &self
279                    .content_type
280                    .as_ref()
281                    .map(|_| "Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>"),
282            )
283            .finish()
284    }
285}
286
287/// Request's payload json parser, it resolves to a deserialized `T` value.
288///
289/// Returns error:
290///
291/// * content type is not `application/json`
292///   (unless specified in [`JsonConfig`])
293/// * content length is greater than the limit (256k by default; the `Json`
294///   extractor sets it from [`JsonConfig`], 32k by default)
295enum JsonBody<U> {
296    Body(super::ReadBody<super::BodyStream>, PhantomData<fn() -> U>),
297    Err(JsonPayloadError),
298    Done,
299}
300
301impl<U> JsonBody<U>
302where
303    U: DeserializeOwned + 'static,
304{
305    /// Create `JsonBody` for request.
306    fn new(
307        req: &HttpRequest,
308        payload: &mut Payload,
309        ctype: Option<&Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
310    ) -> Self {
311        // check content-type
312        let json = if let Ok(Some(mime)) = req.mime_type() {
313            if let Some(predicate) = ctype {
314                predicate(mime)
315            } else {
316                mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON)
317            }
318        } else {
319            false
320        };
321
322        if !json {
323            return Self::err(JsonPayloadError::ContentType);
324        }
325
326        let len = match req.headers().get(&CONTENT_LENGTH).map(|l| {
327            l.to_str()
328                .ok()
329                .and_then(|s| s.parse::<usize>().ok())
330                .ok_or(PayloadError::UnknownLength)
331        }) {
332            None => None,
333            Some(Ok(len)) => Some(len),
334            Some(Err(e)) => return Self::err(JsonPayloadError::Payload(e)),
335        };
336
337        JsonBody::Body(
338            super::ReadBody::from_request(req, payload, 262_144).length(len),
339            PhantomData,
340        )
341    }
342
343    fn err(err: JsonPayloadError) -> Self {
344        JsonBody::Err(err)
345    }
346
347    /// Change max size of payload. By default max size is 256Kb
348    fn limit(mut self, limit: usize) -> Self {
349        if let JsonBody::Body(body, _) = &mut self {
350            body.limit = limit;
351        }
352        self
353    }
354}
355
356impl<U> Future for JsonBody<U>
357where
358    U: DeserializeOwned + 'static,
359{
360    type Output = Result<U, JsonPayloadError>;
361
362    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
363        let this = self.get_mut();
364        let body = match this {
365            JsonBody::Body(body, _) => body,
366            JsonBody::Err(_) => {
367                let JsonBody::Err(err) = mem::replace(this, JsonBody::Done) else {
368                    unreachable!()
369                };
370                return Poll::Ready(Err(err));
371            }
372            JsonBody::Done => panic!("polled after completion"),
373        };
374        if let Some(len) = body.length
375            && len > body.limit
376        {
377            return Poll::Ready(Err(JsonPayloadError::Overflow));
378        }
379        let body = match ready!(Pin::new(body).poll(cx)) {
380            Ok(body) => body,
381            Err(super::ReadBodyError::Overflow(_)) => {
382                return Poll::Ready(Err(JsonPayloadError::Overflow));
383            }
384            Err(super::ReadBodyError::Payload(err)) => {
385                return Poll::Ready(Err(JsonPayloadError::Payload(err)));
386            }
387        };
388        Poll::Ready(crate::http::json::from_slice::<U>(&body).map_err(JsonPayloadError::from))
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395    use crate::http::header;
396    use crate::util::Bytes;
397    use crate::web::test::{TestRequest, from_request, respond_to};
398
399    #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug, thiserror::Error)]
400    #[error("MyObject({name})")]
401    struct MyObject {
402        name: String,
403    }
404
405    fn json_eq(err: &JsonPayloadError, other: &JsonPayloadError) -> bool {
406        if let JsonPayloadError::Overflow = err
407            && let JsonPayloadError::Overflow = other
408        {
409            return true;
410        } else if let JsonPayloadError::ContentType = err
411            && let JsonPayloadError::ContentType = other
412        {
413            return true;
414        }
415        false
416    }
417
418    /// STATEMENT: `Json` exposes mutable data and formatting, and custom configurations remain debuggable.
419    ///
420    /// HOW:
421    /// - Read and change the wrapped object's name and check debug/display output.
422    /// - Install a custom MIME predicate and assert debug output identifies `JsonConfig`.
423    #[test]
424    fn test_json() {
425        let mut j = Json(MyObject {
426            name: "test2".to_string(),
427        });
428        assert_eq!(j.name, "test2");
429        j.name = "test".to_string();
430        assert_eq!(j.name, "test");
431        assert!(format!("{j:?}").contains("Json"));
432        assert!(format!("{j}").contains("test"));
433
434        let cfg = JsonConfig::default().content_type(|mime: mime::Mime| {
435            mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
436        });
437        assert!(format!("{cfg:?}").contains("JsonConfig"));
438    }
439
440    /// STATEMENT: JSON responders serialize wrapped values with the JSON content type.
441    ///
442    /// HOW:
443    /// - Respond with a named object wrapped in `Json`.
444    /// - Assert OK, `application/json`, and the exact serialized body.
445    #[crate::rt_test]
446    async fn test_responder() {
447        let req = TestRequest::default().to_http_request();
448
449        let j = Json(MyObject {
450            name: "test".to_string(),
451        });
452        let resp = respond_to(j, &req).await;
453        assert_eq!(resp.status(), StatusCode::OK);
454        assert_eq!(
455            resp.headers().get(header::CONTENT_TYPE).unwrap(),
456            header::HeaderValue::from_static("application/json")
457        );
458
459        assert_eq!(resp.get_body_ref(), b"{\"name\":\"test\"}");
460    }
461
462    /// STATEMENT: JSON serialization failures become internal-server-error responses.
463    ///
464    /// HOW:
465    /// - Implement a serializer that always fails and wrap its value in `Json`.
466    /// - Render it and assert `INTERNAL_SERVER_ERROR`.
467    #[crate::rt_test]
468    async fn test_responder_serialize_error() {
469        struct Invalid;
470
471        impl Serialize for Invalid {
472            fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
473                Err(serde::ser::Error::custom("invalid"))
474            }
475        }
476
477        let req = TestRequest::default().to_http_request();
478        let resp = respond_to(Json(Invalid), &req).await;
479        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
480    }
481
482    /// STATEMENT: JSON extraction returns decoded objects and reports configured size or syntax errors.
483    ///
484    /// HOW:
485    /// - Extract a valid object and assert its field and `into_inner` value.
486    /// - Set a ten-byte `JsonConfig` limit and assert the overflow error text.
487    /// - Supply malformed JSON and assert it yields a `Deserialize` error whose `JsonError` is a
488    ///   syntax error.
489    #[crate::rt_test]
490    async fn test_extract() {
491        let (req, mut pl, ()) = TestRequest::default()
492            .header(
493                header::CONTENT_TYPE,
494                header::HeaderValue::from_static("application/json"),
495            )
496            .header(
497                header::CONTENT_LENGTH,
498                header::HeaderValue::from_static("16"),
499            )
500            .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
501            .to_http_parts();
502
503        let s = from_request::<_, Json<MyObject>>(&(), &req, &mut pl)
504            .await
505            .unwrap();
506        assert_eq!(s.name, "test");
507        assert_eq!(
508            s.into_inner(),
509            MyObject {
510                name: "test".to_string()
511            }
512        );
513
514        let (req, mut pl, ()) = TestRequest::default()
515            .header(
516                header::CONTENT_TYPE,
517                header::HeaderValue::from_static("application/json"),
518            )
519            .header(
520                header::CONTENT_LENGTH,
521                header::HeaderValue::from_static("16"),
522            )
523            .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
524            .app_value(JsonConfig::default().limit(10))
525            .to_http_parts();
526
527        let s = from_request::<_, Json<MyObject>>(&(), &req, &mut pl).await;
528        assert!(
529            format!("{}", s.err().unwrap()).contains("Json payload size is bigger than allowed")
530        );
531
532        let (req, mut pl, ()) = TestRequest::default()
533            .header(
534                header::CONTENT_TYPE,
535                header::HeaderValue::from_static("application/json"),
536            )
537            .header(
538                header::CONTENT_LENGTH,
539                header::HeaderValue::from_static("16"),
540            )
541            .payload(Bytes::from_static(b"--name-: -test--"))
542            .to_http_parts();
543        let s = from_request::<_, Json<serde_json::Value>>(&(), &req, &mut pl).await;
544        let err = s.err().unwrap();
545        assert!(format!("{err:?}").contains("Deserialize(JsonError("));
546        assert!(matches!(err, JsonPayloadError::Deserialize(ref e) if e.is_syntax()));
547    }
548
549    /// STATEMENT: `Json` reads its config from the `WebAppConfig` value store, never from application state.
550    ///
551    /// HOW:
552    /// - Put a 10-byte `JsonConfig` in `AppState` only and assert a 16-byte body still decodes.
553    /// - Store the same config through the deprecated `TestRequest::app_state()` alias and
554    ///   assert the size-limit error, showing the alias writes the extractor value store.
555    #[crate::rt_test]
556    async fn test_config_not_read_from_state() {
557        let req = || {
558            TestRequest::default()
559                .header(
560                    header::CONTENT_TYPE,
561                    header::HeaderValue::from_static("application/json"),
562                )
563                .header(
564                    header::CONTENT_LENGTH,
565                    header::HeaderValue::from_static("16"),
566                )
567                .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
568        };
569
570        let (http_req, mut pl, st) = req()
571            .state(crate::web::AppState::new(JsonConfig::default().limit(10)))
572            .to_http_parts();
573        let s = from_request::<_, Json<MyObject>>(&st, &http_req, &mut pl).await;
574        assert_eq!(s.unwrap().name, "test");
575
576        #[allow(deprecated)]
577        let (http_req, mut pl, ()) = req()
578            .app_state(JsonConfig::default().limit(10))
579            .to_http_parts();
580        let s = from_request::<_, Json<MyObject>>(&(), &http_req, &mut pl).await;
581        assert!(
582            format!("{}", s.err().unwrap()).contains("Json payload size is bigger than allowed")
583        );
584    }
585
586    /// STATEMENT: `JsonBody` validates media types and lengths before decoding valid JSON.
587    ///
588    /// HOW:
589    /// - Check absent/wrong content types and an oversized declared length return the expected variants.
590    /// - Decode a valid object and assert its value.
591    /// - Use a malformed length and assert a nested `PayloadError::UnknownLength`.
592    #[crate::rt_test]
593    async fn test_json_body() {
594        let (req, mut pl, ()) = TestRequest::default().to_http_parts();
595        let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
596        assert!(json_eq(
597            &json.err().unwrap(),
598            &JsonPayloadError::ContentType
599        ));
600
601        let (req, mut pl, ()) = TestRequest::default()
602            .header(
603                header::CONTENT_TYPE,
604                header::HeaderValue::from_static("application/text"),
605            )
606            .to_http_parts();
607        let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
608        assert!(json_eq(
609            &json.err().unwrap(),
610            &JsonPayloadError::ContentType
611        ));
612
613        let (req, mut pl, ()) = TestRequest::default()
614            .header(
615                header::CONTENT_TYPE,
616                header::HeaderValue::from_static("application/json"),
617            )
618            .header(
619                header::CONTENT_LENGTH,
620                header::HeaderValue::from_static("10000"),
621            )
622            .to_http_parts();
623
624        let json = JsonBody::<MyObject>::new(&req, &mut pl, None)
625            .limit(100)
626            .await;
627        assert!(json_eq(&json.err().unwrap(), &JsonPayloadError::Overflow));
628
629        let (req, mut pl, ()) = TestRequest::default()
630            .header(
631                header::CONTENT_TYPE,
632                header::HeaderValue::from_static("application/json"),
633            )
634            .header(
635                header::CONTENT_LENGTH,
636                header::HeaderValue::from_static("16"),
637            )
638            .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
639            .to_http_parts();
640
641        let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
642        assert_eq!(
643            json.ok().unwrap(),
644            MyObject {
645                name: "test".to_owned()
646            }
647        );
648
649        let (req, mut pl, ()) = TestRequest::default()
650            .header(
651                header::CONTENT_TYPE,
652                header::HeaderValue::from_static("application/json"),
653            )
654            .header(
655                header::CONTENT_LENGTH,
656                header::HeaderValue::from_static("16x"),
657            )
658            .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
659            .to_http_parts();
660
661        let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
662        assert!(matches!(
663            json.err().unwrap(),
664            JsonPayloadError::Payload(PayloadError::UnknownLength)
665        ));
666    }
667
668    /// STATEMENT: Default JSON extraction rejects a plain-text media type even with valid JSON bytes.
669    ///
670    /// HOW:
671    /// - Supply valid JSON as `text/plain` with a configured size limit.
672    /// - Extract `Json<MyObject>` and assert failure.
673    #[crate::rt_test]
674    async fn test_with_json_and_bad_content_type() {
675        let (req, mut pl, ()) = TestRequest::with_header(
676            header::CONTENT_TYPE,
677            header::HeaderValue::from_static("text/plain"),
678        )
679        .header(
680            header::CONTENT_LENGTH,
681            header::HeaderValue::from_static("16"),
682        )
683        .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
684        .app_value(JsonConfig::default().limit(4096))
685        .to_http_parts();
686
687        let s = from_request::<_, Json<MyObject>>(&(), &req, &mut pl).await;
688        assert!(s.is_err());
689    }
690
691    /// STATEMENT: A custom JSON content-type predicate can accept plain-text requests.
692    ///
693    /// HOW:
694    /// - Supply valid JSON as `text/plain` and configure a predicate accepting that MIME type.
695    /// - Extract `Json<MyObject>` and assert success.
696    #[crate::rt_test]
697    async fn test_with_json_and_good_custom_content_type() {
698        let (req, mut pl, ()) = TestRequest::with_header(
699            header::CONTENT_TYPE,
700            header::HeaderValue::from_static("text/plain"),
701        )
702        .header(
703            header::CONTENT_LENGTH,
704            header::HeaderValue::from_static("16"),
705        )
706        .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
707        .app_value(JsonConfig::default().content_type(|mime: mime::Mime| {
708            mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
709        }))
710        .to_http_parts();
711
712        let s = from_request::<_, Json<MyObject>>(&(), &req, &mut pl).await;
713        assert!(s.is_ok());
714    }
715
716    /// STATEMENT: Custom JSON content-type predicates still reject nonmatching media types.
717    ///
718    /// HOW:
719    /// - Supply valid JSON as `text/html` while the predicate accepts only `text/plain`.
720    /// - Extract `Json<MyObject>` and assert failure.
721    #[crate::rt_test]
722    async fn test_with_json_and_bad_custom_content_type() {
723        let (req, mut pl, ()) = TestRequest::with_header(
724            header::CONTENT_TYPE,
725            header::HeaderValue::from_static("text/html"),
726        )
727        .header(
728            header::CONTENT_LENGTH,
729            header::HeaderValue::from_static("16"),
730        )
731        .payload(Bytes::from_static(b"{\"name\": \"test\"}"))
732        .app_value(JsonConfig::default().content_type(|mime: mime::Mime| {
733            mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
734        }))
735        .to_http_parts();
736
737        let s = from_request::<_, Json<MyObject>>(&(), &req, &mut pl).await;
738        assert!(s.is_err());
739    }
740
741    /// STATEMENT: A `JsonConfig::content_type()` predicate replaces the built-in JSON media-type check.
742    ///
743    /// HOW:
744    /// - Without a predicate, assert `application/json`, `text/json` and `application/vnd.api+json`
745    ///   decode while `text/plain` fails with `JsonPayloadError::ContentType`.
746    /// - With a predicate accepting only `application/vnd.api+json`, assert that type decodes while
747    ///   `application/json`, `text/json` and `text/plain` fail with `ContentType`.
748    #[crate::rt_test]
749    async fn test_content_type_predicate_replaces_default() {
750        async fn extract(
751            ctype: &'static str,
752            cfg: Option<JsonConfig>,
753        ) -> Result<(), JsonPayloadError> {
754            let mut req = TestRequest::with_header(
755                header::CONTENT_TYPE,
756                header::HeaderValue::from_static(ctype),
757            )
758            .header(
759                header::CONTENT_LENGTH,
760                header::HeaderValue::from_static("16"),
761            )
762            .payload(Bytes::from_static(b"{\"name\": \"test\"}"));
763            if let Some(cfg) = cfg {
764                req = req.app_value(cfg);
765            }
766            let (req, mut pl, ()) = req.to_http_parts();
767            from_request::<_, Json<MyObject>>(&(), &req, &mut pl)
768                .await
769                .map(|j| assert_eq!(j.name, "test"))
770        }
771
772        for ctype in ["application/json", "text/json", "application/vnd.api+json"] {
773            assert!(extract(ctype, None).await.is_ok(), "{ctype}");
774        }
775        assert!(matches!(
776            extract("text/plain", None).await,
777            Err(JsonPayloadError::ContentType)
778        ));
779
780        let only_vnd = || {
781            JsonConfig::default()
782                .content_type(|mime: mime::Mime| mime.essence_str() == "application/vnd.api+json")
783        };
784        assert!(
785            extract("application/vnd.api+json", Some(only_vnd()))
786                .await
787                .is_ok()
788        );
789        for ctype in ["application/json", "text/json", "text/plain"] {
790            assert!(
791                matches!(
792                    extract(ctype, Some(only_vnd())).await,
793                    Err(JsonPayloadError::ContentType)
794                ),
795                "{ctype}"
796            );
797        }
798    }
799}