ntex 4.7.0

Framework for composable network services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
use std::marker::PhantomData;

use crate::http::error::HttpError;
use crate::http::header::{HeaderMap, HeaderName, HeaderValue};
use crate::http::{Response, ResponseBuilder, StatusCode};
use crate::util::{Bytes, BytesMut, Either};

use super::error::{InternalError, WebResponseError};
use super::{HttpRequest, State};

/// Turns a handler's return value into an HTTP response.
///
/// A handler can return any type that implements `Responder`. ntex provides
/// implementations for common values such as responses, strings, byte
/// buffers, [`Json`](super::types::Json), [`Form`](super::types::Form),
/// `Option<T>`, and `Result<T, E>`.
///
/// After the handler finishes, ntex calls [`respond_to()`](Self::respond_to)
/// with the application state and the original request. Custom responders can
/// use them to choose the status, headers, or response body. The conversion is
/// asynchronous, so it can also perform async work when needed.
///
/// For small changes, use [`with_status()`](Self::with_status) or
/// [`with_header()`](Self::with_header) instead of implementing a new
/// responder.
///
/// # Example
///
/// An application type can be returned directly from a handler after it
/// implements `Responder`:
///
/// ```rust
/// use ntex::http::Response;
/// use ntex::web::{self, HttpRequest, Responder};
///
/// struct Greeting(&'static str);
///
/// impl<St: web::State> Responder<St> for Greeting {
///     async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
///         Response::Ok()
///             .content_type("text/plain; charset=utf-8")
///             .body(self.0)
///     }
/// }
///
/// async fn hello() -> Greeting {
///     Greeting("Hello!")
/// }
///
/// let app = web::App::default().route("/", web::get().to(hello));
/// ```
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be returned from a web handler",
    label = "not a `Responder`",
    note = "return `HttpResponse`, `String`, `&'static str`, `Json<T>`, or another `Responder`",
    note = "`Result<T, E>` is a `Responder` when `T: Responder` and `E` implements `WebResponseError<St, St::Error>`"
)]
pub trait Responder<St: State = ()> {
    /// Builds an HTTP response from this value.
    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response;

    /// Replaces the status code produced by this responder.
    ///
    /// The response body and headers are left unchanged.
    ///
    /// ```rust
    /// use ntex::http::StatusCode;
    /// use ntex::web::{HttpRequest, Responder};
    ///
    /// fn index(req: HttpRequest) -> impl Responder {
    ///     "Welcome!".with_status(StatusCode::OK)
    /// }
    /// # fn main() {}
    /// ```
    ///
    /// The override is unconditional. Applied to a `Result`, it also replaces
    /// the status of the error response, so an `Err` that renders
    /// `400 Bad Request` would be sent as, for example, `201 Created` with the
    /// error body. To set a success status only, map the `Ok` value instead:
    ///
    /// ```rust
    /// use ntex::http::StatusCode;
    /// use ntex::web::{Responder, error};
    ///
    /// async fn create(name: String) -> impl Responder {
    ///     let result = if name.is_empty() {
    ///         Err(error::ErrorBadRequest("name is required"))
    ///     } else {
    ///         Ok(name)
    ///     };
    ///     // `Ok` becomes 201 Created, `Err` keeps 400 Bad Request
    ///     result.map(|name| name.with_status(StatusCode::CREATED))
    /// }
    /// # fn main() {}
    /// ```
    fn with_status(self, status: StatusCode) -> CustomResponder<Self, St>
    where
        Self: Sized,
    {
        CustomResponder::new(self).with_status(status)
    }

    /// Sets a header on the response produced by this responder.
    ///
    /// An existing value with the same header name is replaced. On the
    /// returned [`CustomResponder`], further `with_header()` calls add values
    /// and [`CustomResponder::set_header()`] replaces them.
    ///
    /// ```rust
    /// use ntex::web::{self, HttpRequest, Responder};
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)]
    /// struct MyObj {
    ///     name: String,
    /// }
    ///
    /// async fn index(req: HttpRequest) -> impl Responder {
    ///     web::types::Json(
    ///         MyObj { name: "Name".to_string() }
    ///     )
    ///     .with_header("x-version", "1.2.3")
    /// }
    /// # fn main() {}
    /// ```
    fn with_header<K, V>(self, key: K, value: V) -> CustomResponder<Self, St>
    where
        Self: Sized,
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
    {
        CustomResponder::new(self).with_header(key, value)
    }
}

impl<St: State> Responder<St> for Response {
    #[inline]
    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
        self
    }
}

impl<St: State> Responder<St> for ResponseBuilder {
    #[inline]
    async fn respond_to(mut self, _: &St, _: &HttpRequest) -> Response {
        self.build()
    }
}

impl<T, St> Responder<St> for Option<T>
where
    T: Responder<St>,
    St: State,
{
    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response {
        match self {
            Some(t) => t.respond_to(st, req).await,
            None => Response::builder(StatusCode::NOT_FOUND).build(),
        }
    }
}

impl<St, T, E> Responder<St> for Result<T, E>
where
    St: State,
    T: Responder<St>,
    E: WebResponseError<St, St::Error>,
{
    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response {
        match self {
            Ok(val) => val.respond_to(st, req).await,
            Err(e) => e.error_response(st),
        }
    }
}

/// Renders `T`, then replaces its status unconditionally.
///
/// Like [`Responder::with_status()`], this also overrides error statuses when
/// `T` is a `Result`; map the `Ok` value, as in
/// `result.map(|v| (v, StatusCode::CREATED))`, to set a success status only.
impl<St, T> Responder<St> for (T, StatusCode)
where
    St: State,
    T: Responder<St>,
{
    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response {
        let mut res = self.0.respond_to(st, req).await;
        *res.status_mut() = self.1;
        res
    }
}

impl<St: State> Responder<St> for &'static str {
    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
        Response::builder(StatusCode::OK)
            .content_type("text/plain; charset=utf-8")
            .body(self)
    }
}

impl<St: State> Responder<St> for &'static [u8] {
    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
        Response::builder(StatusCode::OK)
            .content_type("application/octet-stream")
            .body(self)
    }
}

impl<St: State> Responder<St> for String {
    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
        Response::builder(StatusCode::OK)
            .content_type("text/plain; charset=utf-8")
            .body(self)
    }
}

impl<St: State> Responder<St> for &String {
    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
        Response::builder(StatusCode::OK)
            .content_type("text/plain; charset=utf-8")
            .body(self)
    }
}

impl<St: State> Responder<St> for Bytes {
    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
        Response::builder(StatusCode::OK)
            .content_type("application/octet-stream")
            .body(self)
    }
}

impl<St: State> Responder<St> for BytesMut {
    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
        Response::builder(StatusCode::OK)
            .content_type("application/octet-stream")
            .body(self)
    }
}

impl Responder<()> for () {
    async fn respond_to(self, (): &(), _: &HttpRequest) -> Response {
        Response::builder(StatusCode::OK).build()
    }
}

/// Allows to override status code and headers for a responder.
#[derive(derive_more::Debug)]
#[debug("CustomResponder")]
pub struct CustomResponder<T: Responder<St>, St: State> {
    responder: T,
    status: Option<StatusCode>,
    headers: Option<HeaderMap>,
    error: Option<HttpError>,
    _t: PhantomData<St>,
}

impl<T: Responder<St>, St: State> CustomResponder<T, St> {
    fn new(responder: T) -> Self {
        CustomResponder {
            responder,
            status: None,
            headers: None,
            error: None,
            _t: PhantomData,
        }
    }

    /// Override a status code for the Responder's response.
    ///
    /// The status replaces whatever the inner responder produced, including
    /// error statuses rendered by a `Result` error. Use
    /// `result.map(|v| v.with_status(status))` to change only the success
    /// status; see [`Responder::with_status()`].
    ///
    /// ```rust
    /// use ntex::http::StatusCode;
    /// use ntex::web::{HttpRequest, Responder};
    ///
    /// fn index(req: HttpRequest) -> impl Responder {
    ///     "Welcome!".with_status(StatusCode::OK)
    /// }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub fn with_status(mut self, status: StatusCode) -> Self {
        self.status = Some(status);
        self
    }

    /// Sets a header on the Responder's response.
    ///
    /// Replaces values with the same name, both those produced by the inner
    /// responder and those added by earlier `set_header()` or
    /// [`with_header()`](Self::with_header) calls. An invalid name or value
    /// makes the response `500 Internal Server Error`.
    ///
    /// ```rust
    /// use ntex::http::StatusCode;
    /// use ntex::web::{HttpRequest, Responder};
    ///
    /// fn index(req: HttpRequest) -> impl Responder {
    ///     "Created"
    ///         .with_status(StatusCode::CREATED)
    ///         .set_header("x-version", "1.2.3")
    /// }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub fn set_header<K, V>(self, key: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
    {
        self.add_header(key, value, false)
    }

    /// Adds a header value to the Responder's response.
    ///
    /// Keeps values added by earlier `with_header()` or
    /// [`set_header()`](Self::set_header) calls, so one name can carry
    /// several values. Values with the same name produced by the inner
    /// responder are still replaced. An invalid name or value makes the
    /// response `500 Internal Server Error`.
    ///
    /// ```rust
    /// use ntex::web::{HttpRequest, Responder};
    ///
    /// fn index(req: HttpRequest) -> impl Responder {
    ///     "Welcome!"
    ///         .with_header("vary", "accept")
    ///         .with_header("vary", "accept-encoding")
    /// }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub fn with_header<K, V>(self, key: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
    {
        self.add_header(key, value, true)
    }

    fn add_header<K, V>(mut self, key: K, value: V, append: bool) -> Self
    where
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
    {
        let header = HeaderName::try_from(key)
            .map_err(Into::into)
            .and_then(|key| Ok((key, HeaderValue::try_from(value).map_err(Into::into)?)));

        match header {
            Ok((key, value)) => {
                let headers = self.headers.get_or_insert_with(HeaderMap::new);
                if append {
                    headers.append(key, value);
                } else {
                    headers.insert(key, value);
                }
            }
            Err(e) => self.error = Some(e),
        }
        self
    }
}

impl<T: Responder<St>, St: State> Responder<St> for CustomResponder<T, St> {
    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response {
        if let Some(err) = self.error {
            return Response::from(err);
        }
        let mut res = self.responder.respond_to(st, req).await;

        if let Some(status) = self.status {
            *res.status_mut() = status;
        }
        if let Some(headers) = self.headers {
            for key in headers.keys() {
                res.headers_mut().remove(key);
            }
            for (k, v) in &headers {
                res.headers_mut().append(k.clone(), v.clone());
            }
        }
        res
    }
}

/// Combines two different responder types into a single type
///
/// ```rust
/// use ntex::{web::HttpResponse, util::Either};
///
/// fn index() -> Either<HttpResponse, &'static str> {
///     if is_a_variant() {
///         // <- choose left variant
///         Either::Left(HttpResponse::BadRequest().body("Bad data"))
///     } else {
///         // <- Right variant
///         Either::Right("Hello!")
///     }
/// }
/// # fn is_a_variant() -> bool { true }
/// # fn main() {}
/// ```
impl<St, A, B> Responder<St> for Either<A, B>
where
    St: State,
    A: Responder<St>,
    B: Responder<St>,
{
    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response {
        match self {
            Either::Left(a) => a.respond_to(st, req).await,
            Either::Right(b) => b.respond_to(st, req).await,
        }
    }
}

impl<St, T> Responder<St> for InternalError<T>
where
    St: State,
    T: std::fmt::Debug + std::fmt::Display + 'static,
{
    async fn respond_to(self, st: &St, _: &HttpRequest) -> Response {
        WebResponseError::<St, St::Error>::error_response(&self, st)
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::http::Response as HttpResponse;
    use crate::http::body::{Body, ResponseBody};
    use crate::http::header::CONTENT_TYPE;
    use crate::web;
    use crate::web::test::{TestRequest, init_service};

    fn responder<T: Responder>(responder: T) -> impl Responder {
        responder
    }

    /// STATEMENT: `Either` responders render the selected branch's response type.
    ///
    /// HOW:
    /// - Return a bad-request builder for an empty query and a string for a nonempty query.
    /// - Request both variants and assert 400 and OK, respectively.
    #[crate::rt_test]
    async fn test_either_responder() {
        let srv = init_service(web::App::new().service(web::resource("/index.html").to(
            async move |req: HttpRequest| {
                if req.query_string().is_empty() {
                    Either::Left(HttpResponse::BadRequest())
                } else {
                    Either::Right("hello")
                }
            },
        )))
        .await;

        let req = TestRequest::with_uri("/index.html").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let req = TestRequest::with_uri("/index.html?query=test").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    /// STATEMENT: Optional responders map `None` to not found and render the value in `Some`.
    ///
    /// HOW:
    /// - Register handlers returning `None` and `Some("some")`.
    /// - Assert 404 for the former and OK with the exact byte body for the latter.
    #[crate::rt_test]
    async fn test_option_responder() {
        let srv = init_service(
            web::App::new()
                .service(web::resource("/none").to(async || Option::<&'static str>::None))
                .service(web::resource("/some").to(async || Some("some"))),
        )
        .await;

        let req = TestRequest::with_uri("/none").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);

        let req = TestRequest::with_uri("/some").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        if let ResponseBody::Body(Body::Bytes(b)) = resp.body() {
            let bytes: Bytes = b.clone();
            assert_eq!(bytes, Bytes::from_static(b"some"));
        } else {
            panic!()
        }
    }

    /// STATEMENT: Text and binary responders preserve bytes and select their corresponding content type.
    ///
    /// HOW:
    /// - Render string, borrowed string, byte slice, `Bytes`, and `BytesMut` values.
    /// - Assert OK, unchanged bytes, and textual or octet-stream content types as appropriate.
    /// - Render an `InternalError` and assert its explicit bad-request status.
    #[crate::rt_test]
    async fn test_responder() {
        let req = TestRequest::default().to_http_request();

        let resp: HttpResponse = responder("test").respond_to(&(), &req).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.get_body_ref(), b"test");
        assert_eq!(
            resp.headers().get(CONTENT_TYPE).unwrap(),
            HeaderValue::from_static("text/plain; charset=utf-8")
        );

        let resp: HttpResponse = responder(&b"test"[..]).respond_to(&(), &req).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.get_body_ref(), b"test");
        assert_eq!(
            resp.headers().get(CONTENT_TYPE).unwrap(),
            HeaderValue::from_static("application/octet-stream")
        );

        let resp: HttpResponse = responder("test".to_string()).respond_to(&(), &req).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.get_body_ref(), b"test");
        assert_eq!(
            resp.headers().get(CONTENT_TYPE).unwrap(),
            HeaderValue::from_static("text/plain; charset=utf-8")
        );

        let resp: HttpResponse = responder(&"test".to_string()).respond_to(&(), &req).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.get_body_ref(), b"test");
        assert_eq!(
            resp.headers().get(CONTENT_TYPE).unwrap(),
            HeaderValue::from_static("text/plain; charset=utf-8")
        );

        let resp: HttpResponse = responder(Bytes::from_static(b"test"))
            .respond_to(&(), &req)
            .await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.get_body_ref(), b"test");
        assert_eq!(
            resp.headers().get(CONTENT_TYPE).unwrap(),
            HeaderValue::from_static("application/octet-stream")
        );

        let resp: HttpResponse = responder(BytesMut::from(b"test".as_ref()))
            .respond_to(&(), &req)
            .await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.get_body_ref(), b"test");
        assert_eq!(
            resp.headers().get(CONTENT_TYPE).unwrap(),
            HeaderValue::from_static("application/octet-stream")
        );

        // InternalError
        let resp: HttpResponse = responder(InternalError::new("err", StatusCode::BAD_REQUEST))
            .respond_to(&(), &req)
            .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    /// STATEMENT: Result responders render successful values and delegate failures to error rendering.
    ///
    /// HOW:
    /// - Render an OK string result and assert OK, its bytes, and the text content type.
    /// - Render an `InternalError` result and assert `BAD_REQUEST`.
    #[crate::rt_test]
    async fn test_result_responder() {
        let req = TestRequest::default().to_http_request();

        // Result<I, E>
        let resp: HttpResponse = Responder::<()>::respond_to(
            Ok::<String, std::convert::Infallible>("test".to_string()),
            &(),
            &req,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.get_body_ref(), b"test");
        assert_eq!(
            resp.headers().get(CONTENT_TYPE).unwrap(),
            HeaderValue::from_static("text/plain; charset=utf-8")
        );

        let res = responder(Err::<String, _>(InternalError::new(
            "err",
            StatusCode::BAD_REQUEST,
        )))
        .respond_to(&(), &req)
        .await;
        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
    }

    /// STATEMENT: Responder customization overrides status or headers without changing body bytes.
    ///
    /// HOW:
    /// - Apply `with_status` to a string responder and assert 400 with the original body.
    /// - Apply `with_header` and assert OK, the original body, and the replacement content type.
    #[crate::rt_test]
    async fn test_custom_responder() {
        let req = TestRequest::default().to_http_request();
        let res = responder("test".to_string())
            .with_status(StatusCode::BAD_REQUEST)
            .respond_to(&(), &req)
            .await;
        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
        assert_eq!(res.get_body_ref(), b"test");

        let res = responder("test".to_string())
            .with_header("content-type", "json")
            .respond_to(&(), &req)
            .await;

        assert_eq!(res.status(), StatusCode::OK);
        assert_eq!(res.get_body_ref(), b"test");
        assert_eq!(
            res.headers().get(CONTENT_TYPE).unwrap(),
            HeaderValue::from_static("json")
        );
    }

    /// STATEMENT: `with_header` keeps every value, `set_header` replaces them, both replace original values, and invalid syntax is rejected.
    ///
    /// HOW:
    /// - Add `x-test` three times with `with_header` and assert all values are kept in order.
    /// - Add two values then `set_header`, and `set_header` then `with_header`, asserting the replaced and appended values.
    /// - Replace multiple original content types with `with_header` and with `set_header`, asserting only the custom value remains.
    /// - Supply an invalid name and a newline-containing value (also via `set_header`) and assert 500 responses.
    /// - Assert the invalid value is absent even when a successful status override was requested.
    #[crate::rt_test]
    async fn test_custom_responder_headers() {
        let req = TestRequest::default().to_http_request();
        let res = responder("test".to_string())
            .with_header("x-test", "1")
            .with_header("x-test", "2")
            .with_header("x-test", "3")
            .respond_to(&(), &req)
            .await;
        assert_eq!(res.status(), StatusCode::OK);
        let values: Vec<_> = res.headers().get_all("x-test").collect();
        assert_eq!(
            values,
            [
                HeaderValue::from_static("1"),
                HeaderValue::from_static("2"),
                HeaderValue::from_static("3")
            ]
        );

        let res = responder("test".to_string())
            .with_header("x-test", "1")
            .with_header("x-test", "2")
            .set_header("x-test", "3")
            .respond_to(&(), &req)
            .await;
        let values: Vec<_> = res.headers().get_all("x-test").collect();
        assert_eq!(values, [HeaderValue::from_static("3")]);

        let res = CustomResponder::<_, ()>::new(responder("test".to_string()))
            .set_header("x-test", "1")
            .set_header("x-test", "2")
            .with_header("x-test", "3")
            .respond_to(&(), &req)
            .await;
        let values: Vec<_> = res.headers().get_all("x-test").collect();
        assert_eq!(
            values,
            [HeaderValue::from_static("2"), HeaderValue::from_static("3")]
        );

        // header set by the responder is replaced
        let original = || {
            responder(
                HttpResponse::Ok()
                    .header(CONTENT_TYPE, "text/plain")
                    .header(CONTENT_TYPE, "text/html")
                    .build(),
            )
        };
        let res = original()
            .with_header(CONTENT_TYPE, "json")
            .respond_to(&(), &req)
            .await;
        let values: Vec<_> = res.headers().get_all(CONTENT_TYPE).collect();
        assert_eq!(values, [HeaderValue::from_static("json")]);

        let res = CustomResponder::<_, ()>::new(original())
            .set_header(CONTENT_TYPE, "json")
            .respond_to(&(), &req)
            .await;
        let values: Vec<_> = res.headers().get_all(CONTENT_TYPE).collect();
        assert_eq!(values, [HeaderValue::from_static("json")]);

        let res = responder("test".to_string())
            .with_header("bad header", "1")
            .respond_to(&(), &req)
            .await;
        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);

        let res = CustomResponder::<_, ()>::new(responder("test".to_string()))
            .set_header("x-test", "bad\nvalue")
            .respond_to(&(), &req)
            .await;
        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);

        let res = responder("test".to_string())
            .with_header("x-test", "bad\nvalue")
            .with_status(StatusCode::CREATED)
            .respond_to(&(), &req)
            .await;
        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert!(res.headers().get("x-test").is_none());
    }

    /// STATEMENT: Tuple responders apply their status and support additional header customization.
    ///
    /// HOW:
    /// - Render a string/status tuple and assert the chosen status and original bytes.
    /// - Wrap an OK tuple in `CustomResponder`, override content type, and assert status, body, and header.
    #[crate::rt_test]
    async fn test_tuple_responder_with_status_code() {
        let req = TestRequest::default().to_http_request();
        let res =
            Responder::<()>::respond_to(("test".to_string(), StatusCode::BAD_REQUEST), &(), &req)
                .await;
        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
        assert_eq!(res.get_body_ref(), b"test");

        let req = TestRequest::default().to_http_request();
        let res = CustomResponder::<_, ()>::new(("test".to_string(), StatusCode::OK))
            .with_header("content-type", "json")
            .respond_to(&(), &req)
            .await;
        assert_eq!(res.status(), StatusCode::OK);
        assert_eq!(res.get_body_ref(), b"test");
        assert_eq!(
            res.headers().get(CONTENT_TYPE).unwrap(),
            HeaderValue::from_static("json")
        );
    }

    /// STATEMENT: Status overrides on a `Result` replace error statuses, while mapping only the `Ok` value preserves them.
    ///
    /// HOW:
    /// - Render a `400 Bad Request` `Err` through `with_status(CREATED)` and a `(result, CREATED)` tuple and assert both send `201` with the error body.
    /// - Render the same `Err` through `Result::map` with `with_status(CREATED)` and with a tuple, and assert both keep `400`.
    /// - Render an `Ok` value through both mapped forms and assert they send `201` with the success body.
    #[crate::rt_test]
    async fn test_result_status_override_and_success_only_mapping() {
        let req = TestRequest::default().to_http_request();
        let err = || Err::<&'static str, _>(crate::web::error::ErrorBadRequest("invalid"));

        for res in [
            err()
                .with_status(StatusCode::CREATED)
                .respond_to(&(), &req)
                .await,
            (err(), StatusCode::CREATED).respond_to(&(), &req).await,
        ] {
            assert_eq!(res.status(), StatusCode::CREATED);
            assert_eq!(res.get_body_ref(), b"invalid");
        }

        for res in [
            err()
                .map(|v| v.with_status(StatusCode::CREATED))
                .respond_to(&(), &req)
                .await,
            err()
                .map(|v| (v, StatusCode::CREATED))
                .respond_to(&(), &req)
                .await,
        ] {
            assert_eq!(res.status(), StatusCode::BAD_REQUEST);
            assert_eq!(res.get_body_ref(), b"invalid");
        }

        let ok = || Ok::<_, crate::web::error::InternalError<&'static str>>("created");
        for res in [
            ok().map(|v| v.with_status(StatusCode::CREATED))
                .respond_to(&(), &req)
                .await,
            ok().map(|v| (v, StatusCode::CREATED))
                .respond_to(&(), &req)
                .await,
        ] {
            assert_eq!(res.status(), StatusCode::CREATED);
            assert_eq!(res.get_body_ref(), b"created");
        }
    }
}