Skip to main content

actix_web/types/
json.rs

1//! For JSON helper documentation, see [`Json`].
2
3use std::{
4    future::Future,
5    marker::PhantomData,
6    pin::Pin,
7    sync::Arc,
8    task::{Context, Poll},
9};
10
11use actix_http::{error::PayloadError, Payload};
12use bytes::BytesMut;
13use futures_core::{ready, Stream as _};
14use serde::{de::DeserializeOwned, Serialize};
15
16#[cfg(feature = "__compress")]
17use crate::dev::Decompress;
18use crate::{
19    body::EitherBody,
20    error::{Error, JsonPayloadError},
21    extract::FromRequest,
22    http::header::{ContentLength, Header as _},
23    request::HttpRequest,
24    web, HttpMessage, HttpResponse, Responder,
25};
26
27/// JSON extractor and responder.
28///
29/// `Json` has two uses: JSON responses, and extracting typed data from JSON request payloads.
30///
31/// # Extractor
32/// To extract typed data from a request body, the inner type `T` must implement the
33/// [`serde::Deserialize`] trait.
34///
35/// Use [`JsonConfig`] to configure extraction options.
36///
37/// ```
38/// use actix_web::{post, web, App};
39/// use serde::Deserialize;
40///
41/// #[derive(Deserialize)]
42/// struct Info {
43///     username: String,
44/// }
45///
46/// /// deserialize `Info` from request's body
47/// #[post("/")]
48/// async fn index(info: web::Json<Info>) -> String {
49///     format!("Welcome {}!", info.username)
50/// }
51/// ```
52///
53/// # Responder
54/// The `Json` type  JSON formatted responses. A handler may return a value of type
55/// `Json<T>` where `T` is the type of a structure to serialize into JSON. The type `T` must
56/// implement [`serde::Serialize`].
57///
58/// ```
59/// use actix_web::{post, web, HttpRequest};
60/// use serde::Serialize;
61///
62/// #[derive(Serialize)]
63/// struct Info {
64///     name: String,
65/// }
66///
67/// #[post("/{name}")]
68/// async fn index(req: HttpRequest) -> web::Json<Info> {
69///     web::Json(Info {
70///         name: req.match_info().get("name").unwrap().to_owned(),
71///     })
72/// }
73/// ```
74#[derive(Debug)]
75pub struct Json<T>(pub T);
76
77impl_more::impl_deref_and_mut!(<T> in Json<T> => T);
78impl_more::forward_display!(<T> in Json<T>);
79
80impl<T> Json<T> {
81    /// Unwrap into inner `T` value.
82    pub fn into_inner(self) -> T {
83        self.0
84    }
85}
86
87impl<T: Serialize> Serialize for Json<T> {
88    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
89    where
90        S: serde::Serializer,
91    {
92        self.0.serialize(serializer)
93    }
94}
95
96/// Creates response with OK status code, correct content type header, and serialized JSON payload.
97///
98/// If serialization failed
99impl<T: Serialize> Responder for Json<T> {
100    type Body = EitherBody<String>;
101
102    fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> {
103        match serde_json::to_string(&self.0) {
104            Ok(body) => match HttpResponse::Ok()
105                .content_type(mime::APPLICATION_JSON)
106                .message_body(body)
107            {
108                Ok(res) => res.map_into_left_body(),
109                Err(err) => HttpResponse::from_error(err).map_into_right_body(),
110            },
111
112            Err(err) => {
113                HttpResponse::from_error(JsonPayloadError::Serialize(err)).map_into_right_body()
114            }
115        }
116    }
117}
118
119/// See [here](#extractor) for example of usage as an extractor.
120impl<T: DeserializeOwned> FromRequest for Json<T> {
121    type Error = Error;
122    type Future = JsonExtractFut<T>;
123
124    #[inline]
125    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
126        let config = JsonConfig::from_req(req);
127
128        let limit = config.limit;
129        let ctype_required = config.content_type_required;
130        let ctype_fn = config.content_type.as_deref();
131        let err_handler = config.err_handler.clone();
132
133        JsonExtractFut {
134            req: Some(req.clone()),
135            fut: JsonBody::new(req, payload, ctype_fn, ctype_required).limit(limit),
136            err_handler,
137        }
138    }
139}
140
141type JsonErrorHandler = Option<Arc<dyn Fn(JsonPayloadError, &HttpRequest) -> Error + Send + Sync>>;
142
143pub struct JsonExtractFut<T> {
144    req: Option<HttpRequest>,
145    fut: JsonBody<T>,
146    err_handler: JsonErrorHandler,
147}
148
149impl<T: DeserializeOwned> Future for JsonExtractFut<T> {
150    type Output = Result<Json<T>, Error>;
151
152    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
153        let this = self.get_mut();
154
155        let res = ready!(Pin::new(&mut this.fut).poll(cx));
156
157        let res = match res {
158            Err(err) => {
159                let req = this.req.take().unwrap();
160                log::debug!(
161                    "Failed to deserialize Json from payload. \
162                         Request path: {}",
163                    req.path()
164                );
165
166                if let Some(err_handler) = this.err_handler.as_ref() {
167                    Err((*err_handler)(err, &req))
168                } else {
169                    Err(err.into())
170                }
171            }
172            Ok(data) => Ok(Json(data)),
173        };
174
175        Poll::Ready(res)
176    }
177}
178
179/// `Json` extractor configuration.
180///
181/// # Examples
182/// ```
183/// use actix_web::{error, post, web, App, FromRequest, HttpResponse};
184/// use serde::Deserialize;
185///
186/// #[derive(Deserialize)]
187/// struct Info {
188///     name: String,
189/// }
190///
191/// // `Json` extraction is bound by custom `JsonConfig` applied to App.
192/// #[post("/")]
193/// async fn index(info: web::Json<Info>) -> String {
194///     format!("Welcome {}!", info.name)
195/// }
196///
197/// // custom `Json` extractor configuration
198/// let json_cfg = web::JsonConfig::default()
199///     // limit request payload size
200///     .limit(4096)
201///     // only accept text/plain content type
202///     .content_type(|mime| mime == mime::TEXT_PLAIN)
203///     // use custom error handler
204///     .error_handler(|err, req| {
205///         error::InternalError::from_response(err, HttpResponse::Conflict().into()).into()
206///     });
207///
208/// App::new()
209///     .app_data(json_cfg)
210///     .service(index);
211/// ```
212#[derive(Clone)]
213pub struct JsonConfig {
214    limit: usize,
215    err_handler: JsonErrorHandler,
216    content_type: Option<Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
217    content_type_required: bool,
218}
219
220impl JsonConfig {
221    /// Set maximum accepted payload size. By default this limit is 2MB.
222    pub fn limit(mut self, limit: usize) -> Self {
223        self.limit = limit;
224        self
225    }
226
227    /// Set custom error handler.
228    pub fn error_handler<F>(mut self, f: F) -> Self
229    where
230        F: Fn(JsonPayloadError, &HttpRequest) -> Error + Send + Sync + 'static,
231    {
232        self.err_handler = Some(Arc::new(f));
233        self
234    }
235
236    /// Set predicate for allowed content types.
237    pub fn content_type<F>(mut self, predicate: F) -> Self
238    where
239        F: Fn(mime::Mime) -> bool + Send + Sync + 'static,
240    {
241        self.content_type = Some(Arc::new(predicate));
242        self
243    }
244
245    /// Sets whether or not the request must have a `Content-Type` header to be parsed.
246    pub fn content_type_required(mut self, content_type_required: bool) -> Self {
247        self.content_type_required = content_type_required;
248        self
249    }
250
251    /// Extract payload config from app data. Check both `T` and `Data<T>`, in that order, and fall
252    /// back to the default payload config.
253    fn from_req(req: &HttpRequest) -> &Self {
254        req.app_data::<Self>()
255            .or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref()))
256            .unwrap_or(&DEFAULT_CONFIG)
257    }
258}
259
260const DEFAULT_LIMIT: usize = 2_097_152; // 2 mb
261
262/// Allow shared refs used as default.
263const DEFAULT_CONFIG: JsonConfig = JsonConfig {
264    limit: DEFAULT_LIMIT,
265    err_handler: None,
266    content_type: None,
267    content_type_required: true,
268};
269
270impl Default for JsonConfig {
271    fn default() -> Self {
272        DEFAULT_CONFIG
273    }
274}
275
276/// Future that resolves to some `T` when parsed from a JSON payload.
277///
278/// Can deserialize any type `T` that implements [`Deserialize`][serde::Deserialize].
279///
280/// Returns error if:
281/// - `Content-Type` is not `application/json` when `ctype_required` (passed to [`new`][Self::new])
282///   is `true`.
283/// - `Content-Length` is greater than [limit](JsonBody::limit()).
284/// - The payload, when consumed, is not valid JSON.
285pub enum JsonBody<T> {
286    Error(Option<JsonPayloadError>),
287    Body {
288        limit: usize,
289        /// Length as reported by `Content-Length` header, if present.
290        length: Option<usize>,
291        #[cfg(feature = "__compress")]
292        payload: Decompress<Payload>,
293        #[cfg(not(feature = "__compress"))]
294        payload: Payload,
295        buf: BytesMut,
296        _res: PhantomData<T>,
297    },
298}
299
300impl<T> Unpin for JsonBody<T> {}
301
302impl<T: DeserializeOwned> JsonBody<T> {
303    /// Create a new future to decode a JSON request payload.
304    #[allow(clippy::borrow_interior_mutable_const)]
305    pub fn new(
306        req: &HttpRequest,
307        payload: &mut Payload,
308        ctype_fn: Option<&(dyn Fn(mime::Mime) -> bool + Send + Sync)>,
309        ctype_required: bool,
310    ) -> Self {
311        // check content-type
312        let can_parse_json = match (ctype_required, req.mime_type()) {
313            (true, Ok(Some(mime))) => {
314                mime.subtype() == mime::JSON
315                    || mime.suffix() == Some(mime::JSON)
316                    || ctype_fn.is_some_and(|predicate| predicate(mime))
317            }
318
319            // if content-type is expected but not parsable as mime type, bail
320            (true, _) => false,
321
322            // if content-type validation is disabled, assume payload is JSON
323            // even when content-type header is missing or invalid mime type
324            (false, _) => true,
325        };
326
327        if !can_parse_json {
328            return JsonBody::Error(Some(JsonPayloadError::ContentType));
329        }
330
331        let length = ContentLength::parse(req).ok().map(|x| x.0);
332
333        // Notice the content-length is not checked against limit of json config here.
334        // As the internal usage always call JsonBody::limit after JsonBody::new.
335        // And limit check to return an error variant of JsonBody happens there.
336
337        let payload = {
338            cfg_if::cfg_if! {
339                if #[cfg(feature = "__compress")] {
340                    Decompress::from_headers(payload.take(), req.headers())
341                        .limit(DEFAULT_LIMIT)
342                } else {
343                    payload.take()
344                }
345            }
346        };
347
348        JsonBody::Body {
349            limit: DEFAULT_LIMIT,
350            length,
351            payload,
352            buf: BytesMut::with_capacity(8192),
353            _res: PhantomData,
354        }
355    }
356
357    /// Set maximum accepted payload size. The default limit is 2MB.
358    pub fn limit(self, limit: usize) -> Self {
359        match self {
360            JsonBody::Body {
361                length,
362                payload,
363                buf,
364                ..
365            } => {
366                if let Some(len) = length {
367                    if len > limit {
368                        return JsonBody::Error(Some(JsonPayloadError::OverflowKnownLength {
369                            length: len,
370                            limit,
371                        }));
372                    }
373                }
374
375                #[cfg(feature = "__compress")]
376                let payload = payload.limit(limit);
377
378                JsonBody::Body {
379                    limit,
380                    length,
381                    payload,
382                    buf,
383                    _res: PhantomData,
384                }
385            }
386            JsonBody::Error(err) => JsonBody::Error(err),
387        }
388    }
389}
390
391impl<T: DeserializeOwned> Future for JsonBody<T> {
392    type Output = Result<T, JsonPayloadError>;
393
394    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
395        let this = self.get_mut();
396
397        match this {
398            JsonBody::Body {
399                limit,
400                buf,
401                payload,
402                ..
403            } => loop {
404                let res = ready!(Pin::new(&mut *payload).poll_next(cx));
405                match res {
406                    Some(chunk) => {
407                        let chunk = chunk.map_err(|err| match err {
408                            PayloadError::Overflow => JsonPayloadError::Overflow { limit: *limit },
409                            err => JsonPayloadError::Payload(err),
410                        })?;
411                        let buf_len = buf.len() + chunk.len();
412                        if buf_len > *limit {
413                            return Poll::Ready(Err(JsonPayloadError::Overflow { limit: *limit }));
414                        } else {
415                            buf.extend_from_slice(&chunk);
416                        }
417                    }
418                    None => {
419                        let json = serde_json::from_slice::<T>(buf)
420                            .map_err(JsonPayloadError::Deserialize)?;
421                        return Poll::Ready(Ok(json));
422                    }
423                }
424            },
425            JsonBody::Error(err) => Poll::Ready(Err(err.take().unwrap())),
426        }
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use bytes::Bytes;
433    use serde::{Deserialize, Serialize};
434
435    use super::*;
436    use crate::{
437        body,
438        error::InternalError,
439        http::{
440            header::{self, CONTENT_LENGTH, CONTENT_TYPE},
441            StatusCode,
442        },
443        test::{assert_body_eq, TestRequest},
444    };
445
446    #[derive(Serialize, Deserialize, PartialEq, Debug)]
447    struct MyObject {
448        name: String,
449    }
450
451    fn json_eq(err: JsonPayloadError, other: JsonPayloadError) -> bool {
452        match err {
453            JsonPayloadError::Overflow { .. } => {
454                matches!(other, JsonPayloadError::Overflow { .. })
455            }
456            JsonPayloadError::OverflowKnownLength { .. } => {
457                matches!(other, JsonPayloadError::OverflowKnownLength { .. })
458            }
459            JsonPayloadError::ContentType => matches!(other, JsonPayloadError::ContentType),
460            _ => false,
461        }
462    }
463
464    #[tokio::test(flavor = "local")]
465    async fn test_responder() {
466        let req = TestRequest::default().to_http_request();
467
468        let j = Json(MyObject {
469            name: "test".to_string(),
470        });
471        let res = j.respond_to(&req);
472        assert_eq!(res.status(), StatusCode::OK);
473        assert_eq!(
474            res.headers().get(header::CONTENT_TYPE).unwrap(),
475            header::HeaderValue::from_static("application/json")
476        );
477        assert_body_eq!(res, b"{\"name\":\"test\"}");
478    }
479
480    #[tokio::test(flavor = "local")]
481    async fn test_custom_error_responder() {
482        let (req, mut pl) = TestRequest::default()
483            .insert_header((
484                header::CONTENT_TYPE,
485                header::HeaderValue::from_static("application/json"),
486            ))
487            .insert_header((
488                header::CONTENT_LENGTH,
489                header::HeaderValue::from_static("16"),
490            ))
491            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
492            .app_data(JsonConfig::default().limit(10).error_handler(|err, _| {
493                let msg = MyObject {
494                    name: "invalid request".to_string(),
495                };
496                let resp = HttpResponse::BadRequest().body(serde_json::to_string(&msg).unwrap());
497                InternalError::from_response(err, resp).into()
498            }))
499            .to_http_parts();
500
501        let s = Json::<MyObject>::from_request(&req, &mut pl).await;
502        let resp = HttpResponse::from_error(s.unwrap_err());
503        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
504
505        let body = body::to_bytes(resp.into_body()).await.unwrap();
506        let msg: MyObject = serde_json::from_slice(&body).unwrap();
507        assert_eq!(msg.name, "invalid request");
508    }
509
510    #[tokio::test(flavor = "local")]
511    async fn test_extract() {
512        let (req, mut pl) = TestRequest::default()
513            .insert_header((
514                header::CONTENT_TYPE,
515                header::HeaderValue::from_static("application/json"),
516            ))
517            .insert_header((
518                header::CONTENT_LENGTH,
519                header::HeaderValue::from_static("16"),
520            ))
521            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
522            .to_http_parts();
523
524        let s = Json::<MyObject>::from_request(&req, &mut pl).await.unwrap();
525        assert_eq!(s.name, "test");
526        assert_eq!(
527            s.into_inner(),
528            MyObject {
529                name: "test".to_string()
530            }
531        );
532
533        let (req, mut pl) = TestRequest::default()
534            .insert_header((
535                header::CONTENT_TYPE,
536                header::HeaderValue::from_static("application/json"),
537            ))
538            .insert_header((
539                header::CONTENT_LENGTH,
540                header::HeaderValue::from_static("16"),
541            ))
542            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
543            .app_data(JsonConfig::default().limit(10))
544            .to_http_parts();
545
546        let s = Json::<MyObject>::from_request(&req, &mut pl).await;
547        assert!(format!("{}", s.err().unwrap())
548            .contains("JSON payload (16 bytes) is larger than allowed (limit: 10 bytes)"));
549
550        let (req, mut pl) = TestRequest::default()
551            .insert_header((
552                header::CONTENT_TYPE,
553                header::HeaderValue::from_static("application/json"),
554            ))
555            .insert_header((
556                header::CONTENT_LENGTH,
557                header::HeaderValue::from_static("16"),
558            ))
559            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
560            .app_data(
561                JsonConfig::default()
562                    .limit(10)
563                    .error_handler(|_, _| JsonPayloadError::ContentType.into()),
564            )
565            .to_http_parts();
566        let s = Json::<MyObject>::from_request(&req, &mut pl).await;
567        assert!(format!("{}", s.err().unwrap()).contains("Content type error"));
568    }
569
570    #[tokio::test(flavor = "local")]
571    async fn test_json_body() {
572        let (req, mut pl) = TestRequest::default().to_http_parts();
573        let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true).await;
574        assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
575
576        let (req, mut pl) = TestRequest::default()
577            .insert_header((
578                header::CONTENT_TYPE,
579                header::HeaderValue::from_static("application/text"),
580            ))
581            .to_http_parts();
582        let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true).await;
583        assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
584
585        let (req, mut pl) = TestRequest::default()
586            .insert_header((
587                header::CONTENT_TYPE,
588                header::HeaderValue::from_static("application/json"),
589            ))
590            .insert_header((
591                header::CONTENT_LENGTH,
592                header::HeaderValue::from_static("10000"),
593            ))
594            .to_http_parts();
595
596        let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true)
597            .limit(100)
598            .await;
599        assert!(json_eq(
600            json.err().unwrap(),
601            JsonPayloadError::OverflowKnownLength {
602                length: 10000,
603                limit: 100
604            }
605        ));
606
607        let (mut req, mut pl) = TestRequest::default()
608            .insert_header((
609                header::CONTENT_TYPE,
610                header::HeaderValue::from_static("application/json"),
611            ))
612            .set_payload(Bytes::from_static(&[0u8; 1000]))
613            .to_http_parts();
614
615        req.head_mut().headers_mut().remove(header::CONTENT_LENGTH);
616        let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true)
617            .limit(100)
618            .await;
619
620        assert!(json_eq(
621            json.err().unwrap(),
622            JsonPayloadError::Overflow { limit: 100 }
623        ));
624
625        let (req, mut pl) = TestRequest::default()
626            .insert_header((
627                header::CONTENT_TYPE,
628                header::HeaderValue::from_static("application/json"),
629            ))
630            .insert_header((
631                header::CONTENT_LENGTH,
632                header::HeaderValue::from_static("16"),
633            ))
634            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
635            .to_http_parts();
636
637        let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true).await;
638        assert_eq!(
639            json.ok().unwrap(),
640            MyObject {
641                name: "test".to_owned()
642            }
643        );
644    }
645
646    #[tokio::test(flavor = "local")]
647    async fn test_with_json_and_bad_content_type() {
648        let (req, mut pl) = TestRequest::default()
649            .insert_header((
650                header::CONTENT_TYPE,
651                header::HeaderValue::from_static("text/plain"),
652            ))
653            .insert_header((
654                header::CONTENT_LENGTH,
655                header::HeaderValue::from_static("16"),
656            ))
657            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
658            .app_data(JsonConfig::default().limit(4096))
659            .to_http_parts();
660
661        let s = Json::<MyObject>::from_request(&req, &mut pl).await;
662        assert!(s.is_err())
663    }
664
665    #[tokio::test(flavor = "local")]
666    async fn test_with_json_and_good_custom_content_type() {
667        let (req, mut pl) = TestRequest::default()
668            .insert_header((
669                header::CONTENT_TYPE,
670                header::HeaderValue::from_static("text/plain"),
671            ))
672            .insert_header((
673                header::CONTENT_LENGTH,
674                header::HeaderValue::from_static("16"),
675            ))
676            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
677            .app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
678                mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
679            }))
680            .to_http_parts();
681
682        let s = Json::<MyObject>::from_request(&req, &mut pl).await;
683        assert!(s.is_ok())
684    }
685
686    #[tokio::test(flavor = "local")]
687    async fn test_with_json_and_bad_custom_content_type() {
688        let (req, mut pl) = TestRequest::default()
689            .insert_header((
690                header::CONTENT_TYPE,
691                header::HeaderValue::from_static("text/html"),
692            ))
693            .insert_header((
694                header::CONTENT_LENGTH,
695                header::HeaderValue::from_static("16"),
696            ))
697            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
698            .app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
699                mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
700            }))
701            .to_http_parts();
702
703        let s = Json::<MyObject>::from_request(&req, &mut pl).await;
704        assert!(s.is_err())
705    }
706
707    #[tokio::test(flavor = "local")]
708    async fn test_json_with_no_content_type() {
709        let (req, mut pl) = TestRequest::default()
710            .insert_header((
711                header::CONTENT_LENGTH,
712                header::HeaderValue::from_static("16"),
713            ))
714            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
715            .app_data(JsonConfig::default().content_type_required(false))
716            .to_http_parts();
717
718        let s = Json::<MyObject>::from_request(&req, &mut pl).await;
719        assert!(s.is_ok())
720    }
721
722    #[tokio::test(flavor = "local")]
723    async fn test_json_ignoring_content_type() {
724        let (req, mut pl) = TestRequest::default()
725            .insert_header((
726                header::CONTENT_LENGTH,
727                header::HeaderValue::from_static("16"),
728            ))
729            .insert_header((
730                header::CONTENT_TYPE,
731                header::HeaderValue::from_static("invalid/value"),
732            ))
733            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
734            .app_data(JsonConfig::default().content_type_required(false))
735            .to_http_parts();
736
737        let s = Json::<MyObject>::from_request(&req, &mut pl).await;
738        assert!(s.is_ok());
739    }
740
741    #[tokio::test(flavor = "local")]
742    async fn test_with_config_in_data_wrapper() {
743        let (req, mut pl) = TestRequest::default()
744            .insert_header((CONTENT_TYPE, mime::APPLICATION_JSON))
745            .insert_header((CONTENT_LENGTH, 16))
746            .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
747            .app_data(web::Data::new(JsonConfig::default().limit(10)))
748            .to_http_parts();
749
750        let s = Json::<MyObject>::from_request(&req, &mut pl).await;
751        assert!(s.is_err());
752
753        let err_str = s.err().unwrap().to_string();
754        assert!(
755            err_str.contains("JSON payload (16 bytes) is larger than allowed (limit: 10 bytes)")
756        );
757    }
758}