Skip to main content

ntex/web/types/
payload.rs

1//! Payload/Bytes/String extractors
2use std::future::{Future, poll_fn, ready};
3use std::{borrow::Cow, convert::Infallible, fmt, mem, pin::Pin, str, sync::Arc};
4use std::{task::Context, task::Poll, task::ready};
5
6use encoding_rs::UTF_8;
7use mime::Mime;
8
9use crate::http::{HttpMessage, error, header};
10use crate::util::{Bytes, Stream};
11use crate::web::{FromRequest, HttpRequest, State, error::PayloadError};
12
13/// Payload extractor returns request's payload stream.
14///
15/// The stream is not decompressed: with `Content-Encoding: gzip`, `deflate` or
16/// `zstd`, it yields the encoded bytes. The `Bytes`, `String`, `Json` and `Form`
17/// extractors decode the body. To decode this stream, wrap it with
18/// `ntex::http::encoding::Decoder::from_headers()` (requires the `compress`
19/// feature).
20///
21/// ## Example
22///
23/// ```rust
24/// use std::future::Future;
25/// use ntex::util::{BytesMut, Stream};
26/// use ntex::web::{self, error, App, HttpResponse};
27///
28/// /// extract binary data from request
29/// async fn index(mut body: web::types::Payload) -> Result<HttpResponse, error::PayloadError>
30/// {
31///     let mut bytes = BytesMut::new();
32///     while let Some(item) = ntex::util::stream_recv(&mut body).await {
33///         bytes.extend_from_slice(&item?);
34///     }
35///
36///     format!("Body {:?}!", bytes);
37///     Ok(HttpResponse::Ok().build())
38/// }
39///
40/// fn main() {
41///     let app = App::default().service(
42///         web::resource("/index.html").route(
43///             web::get().to(index))
44///     );
45/// }
46/// ```
47#[derive(Debug)]
48pub struct Payload(pub crate::http::Payload);
49
50impl Payload {
51    #[inline]
52    /// Deconstruct to a inner value
53    pub fn into_inner(self) -> crate::http::Payload {
54        self.0
55    }
56
57    #[inline]
58    /// Attempt to pull out the next value of this payload.
59    pub async fn recv(&mut self) -> Option<Result<Bytes, error::PayloadError>> {
60        self.0.recv().await
61    }
62
63    #[inline]
64    /// Attempt to pull out the next value of this payload, registering
65    /// the current task for wakeup if the value is not yet available,
66    /// and returning None if the payload is exhausted.
67    pub fn poll_recv(
68        &mut self,
69        cx: &mut Context<'_>,
70    ) -> Poll<Option<Result<Bytes, error::PayloadError>>> {
71        self.0.poll_recv(cx)
72    }
73}
74
75impl Stream for Payload {
76    type Item = Result<Bytes, error::PayloadError>;
77
78    #[inline]
79    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
80        self.poll_recv(cx)
81    }
82}
83
84/// Get request's payload stream
85///
86/// ## Example
87///
88/// ```rust
89/// use std::future::Future;
90/// use ntex::util::{BytesMut, Stream};
91/// use ntex::web::{self, error, App, HttpResponse};
92///
93/// /// extract binary data from request
94/// async fn index(mut body: web::types::Payload) -> Result<HttpResponse, error::PayloadError>
95/// {
96///     let mut bytes = BytesMut::new();
97///     while let Some(item) = ntex::util::stream_recv(&mut body).await {
98///         bytes.extend_from_slice(&item?);
99///     }
100///
101///     format!("Body {:?}!", bytes);
102///     Ok(HttpResponse::Ok().build())
103/// }
104///
105/// fn main() {
106///     let app = App::default().service(
107///         web::resource("/index.html").route(
108///             web::get().to(index))
109///     );
110/// }
111/// ```
112impl<St: State> FromRequest<St> for Payload {
113    type Error = Infallible;
114
115    #[inline]
116    fn from_request(
117        _: &St,
118        _: &HttpRequest,
119        payload: &mut crate::http::Payload,
120    ) -> impl Future<Output = Result<Payload, Self::Error>> {
121        ready(Ok(Payload(payload.take())))
122    }
123}
124
125/// Request binary data from a request's payload.
126///
127/// Loads request's payload and construct Bytes instance.
128///
129/// [`PayloadConfig`] allows to configure
130/// extraction process.
131///
132/// ## Example
133///
134/// ```rust
135/// use ntex::{web, util::Bytes};
136///
137/// /// extract binary data from request
138/// async fn index(body: Bytes) -> String {
139///     format!("Body {:?}!", body)
140/// }
141///
142/// fn main() {
143///     let app = web::App::default().service(
144///         web::resource("/index.html").route(
145///             web::get().to(index))
146///     );
147/// }
148/// ```
149impl<St: State> FromRequest<St> for Bytes {
150    type Error = PayloadError;
151
152    // Checks run when the future is created, so it holds only the body reader
153    fn from_request(
154        _: &St,
155        req: &HttpRequest,
156        payload: &mut crate::http::Payload,
157    ) -> impl Future<Output = Result<Bytes, Self::Error>> {
158        let tmp;
159        let cfg = if let Some(cfg) = req.app_value::<PayloadConfig>() {
160            cfg
161        } else {
162            tmp = PayloadConfig::default();
163            &tmp
164        };
165
166        match cfg.check_mimetype(req) {
167            Ok(()) => HttpMessageBody::new(req, payload).limit(cfg.limit),
168            Err(e) => HttpMessageBody::err(e),
169        }
170    }
171}
172
173/// Extract text information from a request's body.
174///
175/// Text extractor automatically decode body according to the request's charset.
176///
177/// [`PayloadConfig`] allows to configure
178/// extraction process.
179///
180/// ## Example
181///
182/// ```rust
183/// use ntex::web::{self, App, FromRequest, WebAppConfig};
184///
185/// /// extract text data from request
186/// async fn index(text: String) -> String {
187///     format!("Body {}!", text)
188/// }
189///
190/// fn main() {
191///     let cfg = WebAppConfig::new()
192///         .set_value(web::types::PayloadConfig::new(4096)); // <- limit size of the payload
193///
194///     let app = App::default()
195///         .with_config(cfg)
196///         .service(
197///             web::resource("/index.html")
198///                 .route(web::get().to(index))  // <- register handler with extractor params
199///     );
200/// }
201/// ```
202impl<St: State> FromRequest<St> for String {
203    type Error = PayloadError;
204
205    // Checks run when the future is created, so it holds only the body reader
206    fn from_request(
207        _: &St,
208        req: &HttpRequest,
209        payload: &mut crate::http::Payload,
210    ) -> impl Future<Output = Result<String, Self::Error>> {
211        let tmp;
212        let cfg = if let Some(cfg) = req.app_value::<PayloadConfig>() {
213            cfg
214        } else {
215            tmp = PayloadConfig::default();
216            &tmp
217        };
218
219        // check content-type, then charset
220        let checked = cfg
221            .check_mimetype(req)
222            .and_then(|()| req.encoding().map_err(PayloadError::from));
223        let (mut body, encoding) = match checked {
224            Ok(enc) => (HttpMessageBody::new(req, payload).limit(cfg.limit), enc),
225            Err(e) => (HttpMessageBody::err(e), UTF_8),
226        };
227
228        poll_fn(move |cx| {
229            let body = ready!(Pin::new(&mut body).poll(cx))?;
230            Poll::Ready(if encoding == UTF_8 {
231                str::from_utf8(body.as_ref())
232                    .map(str::to_owned)
233                    .map_err(|_| PayloadError::Decoding)
234            } else {
235                encoding
236                    .decode_without_bom_handling_and_without_replacement(&body)
237                    .map(Cow::into_owned)
238                    .ok_or(PayloadError::Decoding)
239            })
240        })
241    }
242}
243
244/// Payload configuration for request's payload.
245///
246/// Register it with [`WebAppConfig::set_value()`](crate::web::WebAppConfig::set_value)
247/// and [`App::with_config()`](crate::web::App::with_config). The extractor
248/// does not read the application state, so a config stored in
249/// [`AppState`](crate::web::AppState) has no effect.
250#[derive(Clone)]
251pub struct PayloadConfig {
252    limit: usize,
253    content_type: Option<Arc<dyn Fn(Mime) -> bool + Send + Sync>>,
254}
255
256impl PayloadConfig {
257    #[must_use]
258    /// Create `PayloadConfig` instance and set max size of payload.
259    pub fn new(limit: usize) -> Self {
260        PayloadConfig {
261            limit,
262            ..Default::default()
263        }
264    }
265
266    #[must_use]
267    /// Change max size of payload.
268    ///
269    /// By default max size is 256Kb.
270    pub fn limit(mut self, limit: usize) -> Self {
271        self.limit = limit;
272        self
273    }
274
275    #[must_use]
276    /// Set predicate for allowed content types.
277    ///
278    /// The predicate receives the request's parsed `Content-Type`. A request
279    /// without a `Content-Type` header, or one the predicate rejects, fails
280    /// with a content-type error. By default the content type is not checked.
281    pub fn content_type<F>(mut self, predicate: F) -> Self
282    where
283        F: Fn(Mime) -> bool + Send + Sync + 'static,
284    {
285        self.content_type = Some(Arc::new(predicate));
286        self
287    }
288
289    #[must_use]
290    /// Set required mime-type of the request.
291    ///
292    /// This is a shorthand for [`content_type`](Self::content_type) with a
293    /// predicate that accepts only `mt`. The comparison includes parameters,
294    /// such as `charset`. By default mime type is not enforced.
295    pub fn mimetype(self, mt: Mime) -> Self {
296        self.content_type(move |req_mt| req_mt == mt)
297    }
298
299    fn check_mimetype(&self, req: &HttpRequest) -> Result<(), PayloadError> {
300        // check content-type
301        if let Some(ref predicate) = self.content_type {
302            match req.mime_type() {
303                Ok(Some(req_mt)) => {
304                    if !predicate(req_mt) {
305                        return Err(PayloadError::from(error::ContentTypeError::Unexpected));
306                    }
307                }
308                Ok(None) => {
309                    return Err(PayloadError::from(error::ContentTypeError::Expected));
310                }
311                Err(err) => {
312                    return Err(err.into());
313                }
314            }
315        }
316        Ok(())
317    }
318}
319
320impl Default for PayloadConfig {
321    fn default() -> Self {
322        PayloadConfig {
323            limit: 262_144,
324            content_type: None,
325        }
326    }
327}
328
329impl fmt::Debug for PayloadConfig {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        f.debug_struct("PayloadConfig")
332            .field("limit", &self.limit)
333            .field(
334                "content_type",
335                &self
336                    .content_type
337                    .as_ref()
338                    .map(|_| "Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>"),
339            )
340            .finish()
341    }
342}
343
344/// Future that resolves to a complete http message body.
345///
346/// Load http message body.
347///
348/// By default only 256Kb payload reads to a memory, then
349/// `PayloadError::Overflow` is returned. Use `HttpMessageBody::limit()`
350/// method to change upper limit.
351enum HttpMessageBody {
352    Body(super::ReadBody<super::BodyStream>),
353    Err(PayloadError),
354    Done,
355}
356
357impl HttpMessageBody {
358    /// Create `MessageBody` for request.
359    fn new(req: &HttpRequest, payload: &mut crate::http::Payload) -> HttpMessageBody {
360        let mut len = None;
361        if let Some(l) = req.headers().get(&header::CONTENT_LENGTH) {
362            if let Ok(s) = l.to_str() {
363                if let Ok(l) = s.parse::<usize>() {
364                    len = Some(l);
365                } else {
366                    return Self::err(PayloadError::Payload(error::PayloadError::UnknownLength));
367                }
368            } else {
369                return Self::err(PayloadError::Payload(error::PayloadError::UnknownLength));
370            }
371        }
372
373        HttpMessageBody::Body(super::ReadBody::from_request(req, payload, 262_144).length(len))
374    }
375
376    /// Change max size of payload. By default max size is 256Kb
377    fn limit(mut self, limit: usize) -> Self {
378        if let HttpMessageBody::Body(body) = &mut self {
379            body.limit = limit;
380        }
381        self
382    }
383
384    fn err(e: PayloadError) -> Self {
385        HttpMessageBody::Err(e)
386    }
387}
388
389impl Future for HttpMessageBody {
390    type Output = Result<Bytes, PayloadError>;
391
392    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
393        let this = self.get_mut();
394        let body = match this {
395            HttpMessageBody::Body(body) => body,
396            HttpMessageBody::Err(_) => {
397                let HttpMessageBody::Err(err) = mem::replace(this, HttpMessageBody::Done) else {
398                    unreachable!()
399                };
400                return Poll::Ready(Err(err));
401            }
402            HttpMessageBody::Done => panic!("polled after completion"),
403        };
404        if let Some(len) = body.length
405            && len > body.limit
406        {
407            return Poll::Ready(Err(PayloadError::from(error::PayloadError::Overflow)));
408        }
409        Pin::new(body).poll(cx).map_err(|err| match err {
410            super::ReadBodyError::Overflow(_) => PayloadError::from(error::PayloadError::Overflow),
411            super::ReadBodyError::Payload(err) => PayloadError::from(err),
412        })
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419    use crate::web::test::{TestRequest, from_request};
420
421    /// STATEMENT: Payload configuration enforces exact or predicate-based media-type requirements.
422    ///
423    /// HOW:
424    /// - Require JSON and assert missing/form types fail while JSON passes.
425    /// - Require plain text through a predicate and assert JSON fails and parameterized plain text passes.
426    /// - Assert debug output identifies `PayloadConfig`.
427    #[crate::rt_test]
428    async fn test_payload_config() {
429        let req = TestRequest::default().to_http_request();
430        let cfg = PayloadConfig::default()
431            .limit(5)
432            .mimetype(mime::APPLICATION_JSON);
433        assert!(cfg.check_mimetype(&req).is_err());
434
435        let req =
436            TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
437                .to_http_request();
438        assert!(cfg.check_mimetype(&req).is_err());
439
440        let req =
441            TestRequest::with_header(header::CONTENT_TYPE, "application/json").to_http_request();
442        assert!(cfg.check_mimetype(&req).is_ok());
443
444        let cfg = PayloadConfig::default()
445            .content_type(|mt| mt.type_() == mime::TEXT && mt.subtype() == mime::PLAIN);
446        let req =
447            TestRequest::with_header(header::CONTENT_TYPE, "application/json").to_http_request();
448        assert!(cfg.check_mimetype(&req).is_err());
449
450        let req = TestRequest::with_header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
451            .to_http_request();
452        assert!(cfg.check_mimetype(&req).is_ok());
453        assert!(format!("{cfg:?}").contains("PayloadConfig"));
454    }
455
456    /// STATEMENT: Body extractors exceeding the payload limit render `413`, other errors `400`.
457    ///
458    /// HOW:
459    /// - Extract `Bytes` and `String` with a five-byte `PayloadConfig`, from a declared
460    ///   and an undeclared longer body, and render each error.
461    /// - Assert `PAYLOAD_TOO_LARGE`, then assert a media-type mismatch renders `BAD_REQUEST`.
462    #[crate::rt_test]
463    async fn test_payload_overflow_status() {
464        use crate::web::{DefaultError, WebResponseError};
465
466        fn status(err: &PayloadError) -> crate::http::StatusCode {
467            WebResponseError::<(), DefaultError>::error_response(err, &()).status()
468        }
469
470        for declared in [true, false] {
471            let mut req = TestRequest::default()
472                .app_value(PayloadConfig::new(5))
473                .payload(Bytes::from_static(b"hello=world"));
474            if declared {
475                req = req.header(header::CONTENT_LENGTH, "11");
476            }
477            let (req, mut pl, ()) = req.to_http_parts();
478            let err = from_request::<_, Bytes>(&(), &req, &mut pl)
479                .await
480                .unwrap_err();
481            assert_eq!(status(&err), crate::http::StatusCode::PAYLOAD_TOO_LARGE);
482
483            let mut req = TestRequest::default()
484                .app_value(PayloadConfig::new(5))
485                .payload(Bytes::from_static(b"hello=world"));
486            if declared {
487                req = req.header(header::CONTENT_LENGTH, "11");
488            }
489            let (req, mut pl, ()) = req.to_http_parts();
490            let err = from_request::<_, String>(&(), &req, &mut pl)
491                .await
492                .unwrap_err();
493            assert_eq!(status(&err), crate::http::StatusCode::PAYLOAD_TOO_LARGE);
494        }
495
496        let (req, mut pl, ()) = TestRequest::default()
497            .app_value(PayloadConfig::default().mimetype(mime::APPLICATION_JSON))
498            .payload(Bytes::from_static(b"hello=world"))
499            .to_http_parts();
500        let err = from_request::<_, Bytes>(&(), &req, &mut pl)
501            .await
502            .unwrap_err();
503        assert_eq!(status(&err), crate::http::StatusCode::BAD_REQUEST);
504    }
505
506    /// STATEMENT: Extracted `Payload` streams expose the request's original bytes.
507    ///
508    /// HOW:
509    /// - Extract `Payload` from a request containing `hello=world`.
510    /// - Receive through `stream_recv` and assert the exact byte chunk.
511    #[crate::rt_test]
512    async fn test_payload() {
513        let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
514            .payload(Bytes::from_static(b"hello=world"))
515            .to_http_parts();
516
517        let mut s = from_request::<_, Payload>(&(), &req, &mut pl)
518            .await
519            .unwrap();
520        let b = crate::util::stream_recv(&mut s).await.unwrap().unwrap();
521        assert_eq!(b, Bytes::from_static(b"hello=world"));
522    }
523
524    /// STATEMENT: `Payload::recv` retrieves the extracted request body chunk.
525    ///
526    /// HOW:
527    /// - Extract a payload containing `hello=world`.
528    /// - Await `recv` and assert its successful bytes match the supplied body.
529    #[crate::rt_test]
530    async fn test_payload_recv() {
531        let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
532            .payload(Bytes::from_static(b"hello=world"))
533            .to_http_parts();
534
535        let mut s = from_request::<_, Payload>(&(), &req, &mut pl)
536            .await
537            .unwrap();
538        let b = s.recv().await.unwrap().unwrap();
539        assert_eq!(b, Bytes::from_static(b"hello=world"));
540    }
541
542    /// STATEMENT: Byte extraction preserves body bytes and honors configured media-type validation.
543    ///
544    /// HOW:
545    /// - Extract `Bytes` from a request and assert the exact body.
546    /// - Require JSON on an otherwise identical request lacking that type and assert extraction fails.
547    #[crate::rt_test]
548    async fn test_bytes() {
549        let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
550            .payload(Bytes::from_static(b"hello=world"))
551            .to_http_parts();
552
553        let s = from_request::<_, Bytes>(&(), &req, &mut pl).await.unwrap();
554        assert_eq!(s, Bytes::from_static(b"hello=world"));
555
556        let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
557            .payload(Bytes::from_static(b"hello=world"))
558            .app_value(PayloadConfig::default().mimetype(mime::APPLICATION_JSON))
559            .to_http_parts();
560        assert!(from_request::<_, Bytes>(&(), &req, &mut pl).await.is_err());
561    }
562
563    /// STATEMENT: String extraction supports default and declared charsets while enforcing MIME constraints.
564    ///
565    /// HOW:
566    /// - Extract the same ASCII body without a charset and with CP1251 and assert the decoded text.
567    /// - Configure a JSON MIME requirement on a request lacking it and assert extraction fails.
568    #[crate::rt_test]
569    async fn test_string() {
570        let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
571            .payload(Bytes::from_static(b"hello=world"))
572            .to_http_parts();
573
574        let s = from_request::<_, String>(&(), &req, &mut pl).await.unwrap();
575        assert_eq!(s, "hello=world");
576
577        let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
578            .header(header::CONTENT_TYPE, "text/plain; charset=cp1251")
579            .payload(Bytes::from_static(b"hello=world"))
580            .to_http_parts();
581        let s = from_request::<_, String>(&(), &req, &mut pl).await.unwrap();
582        assert_eq!(s, "hello=world");
583
584        let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
585            .payload(Bytes::from_static(b"hello=world"))
586            .app_value(PayloadConfig::default().mimetype(mime::APPLICATION_JSON))
587            .to_http_parts();
588        assert!(from_request::<_, String>(&(), &req, &mut pl).await.is_err());
589    }
590
591    /// STATEMENT: `HttpMessageBody` validates declared lengths and limits streamed bodies.
592    ///
593    /// HOW:
594    /// - Assert malformed and oversized content lengths yield `UnknownLength` and `Overflow`.
595    /// - Read a body without a length and assert its bytes.
596    /// - Read a larger undeclared body with a five-byte limit and assert overflow.
597    #[crate::rt_test]
598    async fn test_message_body() {
599        let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "xxxx")
600            .to_srv_request()
601            .into_parts();
602        let res = HttpMessageBody::new(&req, &mut pl).await;
603        match res.err().unwrap() {
604            PayloadError::Payload(error::PayloadError::UnknownLength) => (),
605            _ => unreachable!("error"),
606        }
607
608        let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "1000000")
609            .to_srv_request()
610            .into_parts();
611        let res = HttpMessageBody::new(&req, &mut pl).await;
612        match res.err().unwrap() {
613            PayloadError::Payload(error::PayloadError::Overflow) => (),
614            _ => unreachable!("error"),
615        }
616
617        let (req, mut pl, ()) = TestRequest::default()
618            .payload(Bytes::from_static(b"test"))
619            .to_http_parts();
620        let res = HttpMessageBody::new(&req, &mut pl).await;
621        assert_eq!(res.ok().unwrap(), Bytes::from_static(b"test"));
622
623        let (req, mut pl, ()) = TestRequest::default()
624            .payload(Bytes::from_static(b"11111111111111"))
625            .to_http_parts();
626        let res = HttpMessageBody::new(&req, &mut pl).limit(5).await;
627        match res.err().unwrap() {
628            PayloadError::Payload(error::PayloadError::Overflow) => (),
629            _ => unreachable!("error"),
630        }
631    }
632
633    /// STATEMENT: Payload extraction rejects unknown charsets, malformed MIME types, and non-UTF-8 lengths.
634    ///
635    /// HOW:
636    /// - Check an explicit configuration limit, then assert string extraction rejects an unknown charset.
637    /// - Validate an invalid media type and assert `PayloadError::ContentType`.
638    /// - Read a non-UTF-8 length header and assert the nested `UnknownLength` error.
639    #[crate::rt_test]
640    async fn test_payload_errors() {
641        let cfg = PayloadConfig::new(5);
642        assert_eq!(cfg.limit, 5);
643
644        // invalid charset
645        let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
646            .header(header::CONTENT_TYPE, "text/plain; charset=unknown")
647            .payload(Bytes::from_static(b"hello=world"))
648            .to_http_parts();
649        assert!(from_request::<_, String>(&(), &req, &mut pl).await.is_err());
650
651        // invalid mime type
652        let cfg = PayloadConfig::default().mimetype(mime::APPLICATION_JSON);
653        let req = TestRequest::with_header(header::CONTENT_TYPE, "invalid").to_http_request();
654        assert!(matches!(
655            cfg.check_mimetype(&req),
656            Err(PayloadError::ContentType(_))
657        ));
658
659        // non-ascii content-length
660        let (req, mut pl, ()) = TestRequest::with_header(
661            header::CONTENT_LENGTH,
662            header::HeaderValue::from_bytes(b"1\xff").unwrap(),
663        )
664        .to_http_parts();
665        let res = HttpMessageBody::new(&req, &mut pl).await;
666        assert!(matches!(
667            res,
668            Err(PayloadError::Payload(error::PayloadError::UnknownLength))
669        ));
670    }
671}