Skip to main content

ntex/web/
responder.rs

1use std::marker::PhantomData;
2
3use crate::http::error::HttpError;
4use crate::http::header::{HeaderMap, HeaderName, HeaderValue};
5use crate::http::{Response, ResponseBuilder, StatusCode};
6use crate::util::{Bytes, BytesMut, Either};
7
8use super::error::{InternalError, WebResponseError};
9use super::{HttpRequest, State};
10
11/// Turns a handler's return value into an HTTP response.
12///
13/// A handler can return any type that implements `Responder`. ntex provides
14/// implementations for common values such as responses, strings, byte
15/// buffers, [`Json`](super::types::Json), [`Form`](super::types::Form),
16/// `Option<T>`, and `Result<T, E>`.
17///
18/// After the handler finishes, ntex calls [`respond_to()`](Self::respond_to)
19/// with the application state and the original request. Custom responders can
20/// use them to choose the status, headers, or response body. The conversion is
21/// asynchronous, so it can also perform async work when needed.
22///
23/// For small changes, use [`with_status()`](Self::with_status) or
24/// [`with_header()`](Self::with_header) instead of implementing a new
25/// responder.
26///
27/// # Example
28///
29/// An application type can be returned directly from a handler after it
30/// implements `Responder`:
31///
32/// ```rust
33/// use ntex::http::Response;
34/// use ntex::web::{self, HttpRequest, Responder};
35///
36/// struct Greeting(&'static str);
37///
38/// impl<St: web::State> Responder<St> for Greeting {
39///     async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
40///         Response::Ok()
41///             .content_type("text/plain; charset=utf-8")
42///             .body(self.0)
43///     }
44/// }
45///
46/// async fn hello() -> Greeting {
47///     Greeting("Hello!")
48/// }
49///
50/// let app = web::App::default().route("/", web::get().to(hello));
51/// ```
52#[diagnostic::on_unimplemented(
53    message = "`{Self}` cannot be returned from a web handler",
54    label = "not a `Responder`",
55    note = "return `HttpResponse`, `String`, `&'static str`, `Json<T>`, or another `Responder`",
56    note = "`Result<T, E>` is a `Responder` when `T: Responder` and `E` implements `WebResponseError<St, St::Error>`"
57)]
58pub trait Responder<St: State = ()> {
59    /// Builds an HTTP response from this value.
60    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response;
61
62    /// Replaces the status code produced by this responder.
63    ///
64    /// The response body and headers are left unchanged.
65    ///
66    /// ```rust
67    /// use ntex::http::StatusCode;
68    /// use ntex::web::{HttpRequest, Responder};
69    ///
70    /// fn index(req: HttpRequest) -> impl Responder {
71    ///     "Welcome!".with_status(StatusCode::OK)
72    /// }
73    /// # fn main() {}
74    /// ```
75    ///
76    /// The override is unconditional. Applied to a `Result`, it also replaces
77    /// the status of the error response, so an `Err` that renders
78    /// `400 Bad Request` would be sent as, for example, `201 Created` with the
79    /// error body. To set a success status only, map the `Ok` value instead:
80    ///
81    /// ```rust
82    /// use ntex::http::StatusCode;
83    /// use ntex::web::{Responder, error};
84    ///
85    /// async fn create(name: String) -> impl Responder {
86    ///     let result = if name.is_empty() {
87    ///         Err(error::ErrorBadRequest("name is required"))
88    ///     } else {
89    ///         Ok(name)
90    ///     };
91    ///     // `Ok` becomes 201 Created, `Err` keeps 400 Bad Request
92    ///     result.map(|name| name.with_status(StatusCode::CREATED))
93    /// }
94    /// # fn main() {}
95    /// ```
96    fn with_status(self, status: StatusCode) -> CustomResponder<Self, St>
97    where
98        Self: Sized,
99    {
100        CustomResponder::new(self).with_status(status)
101    }
102
103    /// Sets a header on the response produced by this responder.
104    ///
105    /// An existing value with the same header name is replaced. On the
106    /// returned [`CustomResponder`], further `with_header()` calls add values
107    /// and [`CustomResponder::set_header()`] replaces them.
108    ///
109    /// ```rust
110    /// use ntex::web::{self, HttpRequest, Responder};
111    /// use serde::Serialize;
112    ///
113    /// #[derive(Serialize)]
114    /// struct MyObj {
115    ///     name: String,
116    /// }
117    ///
118    /// async fn index(req: HttpRequest) -> impl Responder {
119    ///     web::types::Json(
120    ///         MyObj { name: "Name".to_string() }
121    ///     )
122    ///     .with_header("x-version", "1.2.3")
123    /// }
124    /// # fn main() {}
125    /// ```
126    fn with_header<K, V>(self, key: K, value: V) -> CustomResponder<Self, St>
127    where
128        Self: Sized,
129        HeaderName: TryFrom<K>,
130        HeaderValue: TryFrom<V>,
131        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
132        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
133    {
134        CustomResponder::new(self).with_header(key, value)
135    }
136}
137
138impl<St: State> Responder<St> for Response {
139    #[inline]
140    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
141        self
142    }
143}
144
145impl<St: State> Responder<St> for ResponseBuilder {
146    #[inline]
147    async fn respond_to(mut self, _: &St, _: &HttpRequest) -> Response {
148        self.build()
149    }
150}
151
152impl<T, St> Responder<St> for Option<T>
153where
154    T: Responder<St>,
155    St: State,
156{
157    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response {
158        match self {
159            Some(t) => t.respond_to(st, req).await,
160            None => Response::builder(StatusCode::NOT_FOUND).build(),
161        }
162    }
163}
164
165impl<St, T, E> Responder<St> for Result<T, E>
166where
167    St: State,
168    T: Responder<St>,
169    E: WebResponseError<St, St::Error>,
170{
171    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response {
172        match self {
173            Ok(val) => val.respond_to(st, req).await,
174            Err(e) => e.error_response(st),
175        }
176    }
177}
178
179/// Renders `T`, then replaces its status unconditionally.
180///
181/// Like [`Responder::with_status()`], this also overrides error statuses when
182/// `T` is a `Result`; map the `Ok` value, as in
183/// `result.map(|v| (v, StatusCode::CREATED))`, to set a success status only.
184impl<St, T> Responder<St> for (T, StatusCode)
185where
186    St: State,
187    T: Responder<St>,
188{
189    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response {
190        let mut res = self.0.respond_to(st, req).await;
191        *res.status_mut() = self.1;
192        res
193    }
194}
195
196impl<St: State> Responder<St> for &'static str {
197    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
198        Response::builder(StatusCode::OK)
199            .content_type("text/plain; charset=utf-8")
200            .body(self)
201    }
202}
203
204impl<St: State> Responder<St> for &'static [u8] {
205    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
206        Response::builder(StatusCode::OK)
207            .content_type("application/octet-stream")
208            .body(self)
209    }
210}
211
212impl<St: State> Responder<St> for String {
213    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
214        Response::builder(StatusCode::OK)
215            .content_type("text/plain; charset=utf-8")
216            .body(self)
217    }
218}
219
220impl<St: State> Responder<St> for &String {
221    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
222        Response::builder(StatusCode::OK)
223            .content_type("text/plain; charset=utf-8")
224            .body(self)
225    }
226}
227
228impl<St: State> Responder<St> for Bytes {
229    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
230        Response::builder(StatusCode::OK)
231            .content_type("application/octet-stream")
232            .body(self)
233    }
234}
235
236impl<St: State> Responder<St> for BytesMut {
237    async fn respond_to(self, _: &St, _: &HttpRequest) -> Response {
238        Response::builder(StatusCode::OK)
239            .content_type("application/octet-stream")
240            .body(self)
241    }
242}
243
244impl Responder<()> for () {
245    async fn respond_to(self, (): &(), _: &HttpRequest) -> Response {
246        Response::builder(StatusCode::OK).build()
247    }
248}
249
250/// Allows to override status code and headers for a responder.
251#[derive(derive_more::Debug)]
252#[debug("CustomResponder")]
253pub struct CustomResponder<T: Responder<St>, St: State> {
254    responder: T,
255    status: Option<StatusCode>,
256    headers: Option<HeaderMap>,
257    error: Option<HttpError>,
258    _t: PhantomData<St>,
259}
260
261impl<T: Responder<St>, St: State> CustomResponder<T, St> {
262    fn new(responder: T) -> Self {
263        CustomResponder {
264            responder,
265            status: None,
266            headers: None,
267            error: None,
268            _t: PhantomData,
269        }
270    }
271
272    /// Override a status code for the Responder's response.
273    ///
274    /// The status replaces whatever the inner responder produced, including
275    /// error statuses rendered by a `Result` error. Use
276    /// `result.map(|v| v.with_status(status))` to change only the success
277    /// status; see [`Responder::with_status()`].
278    ///
279    /// ```rust
280    /// use ntex::http::StatusCode;
281    /// use ntex::web::{HttpRequest, Responder};
282    ///
283    /// fn index(req: HttpRequest) -> impl Responder {
284    ///     "Welcome!".with_status(StatusCode::OK)
285    /// }
286    /// # fn main() {}
287    /// ```
288    #[must_use]
289    pub fn with_status(mut self, status: StatusCode) -> Self {
290        self.status = Some(status);
291        self
292    }
293
294    /// Sets a header on the Responder's response.
295    ///
296    /// Replaces values with the same name, both those produced by the inner
297    /// responder and those added by earlier `set_header()` or
298    /// [`with_header()`](Self::with_header) calls. An invalid name or value
299    /// makes the response `500 Internal Server Error`.
300    ///
301    /// ```rust
302    /// use ntex::http::StatusCode;
303    /// use ntex::web::{HttpRequest, Responder};
304    ///
305    /// fn index(req: HttpRequest) -> impl Responder {
306    ///     "Created"
307    ///         .with_status(StatusCode::CREATED)
308    ///         .set_header("x-version", "1.2.3")
309    /// }
310    /// # fn main() {}
311    /// ```
312    #[must_use]
313    pub fn set_header<K, V>(self, key: K, value: V) -> Self
314    where
315        HeaderName: TryFrom<K>,
316        HeaderValue: TryFrom<V>,
317        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
318        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
319    {
320        self.add_header(key, value, false)
321    }
322
323    /// Adds a header value to the Responder's response.
324    ///
325    /// Keeps values added by earlier `with_header()` or
326    /// [`set_header()`](Self::set_header) calls, so one name can carry
327    /// several values. Values with the same name produced by the inner
328    /// responder are still replaced. An invalid name or value makes the
329    /// response `500 Internal Server Error`.
330    ///
331    /// ```rust
332    /// use ntex::web::{HttpRequest, Responder};
333    ///
334    /// fn index(req: HttpRequest) -> impl Responder {
335    ///     "Welcome!"
336    ///         .with_header("vary", "accept")
337    ///         .with_header("vary", "accept-encoding")
338    /// }
339    /// # fn main() {}
340    /// ```
341    #[must_use]
342    pub fn with_header<K, V>(self, key: K, value: V) -> Self
343    where
344        HeaderName: TryFrom<K>,
345        HeaderValue: TryFrom<V>,
346        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
347        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
348    {
349        self.add_header(key, value, true)
350    }
351
352    fn add_header<K, V>(mut self, key: K, value: V, append: bool) -> Self
353    where
354        HeaderName: TryFrom<K>,
355        HeaderValue: TryFrom<V>,
356        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
357        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
358    {
359        let header = HeaderName::try_from(key)
360            .map_err(Into::into)
361            .and_then(|key| Ok((key, HeaderValue::try_from(value).map_err(Into::into)?)));
362
363        match header {
364            Ok((key, value)) => {
365                let headers = self.headers.get_or_insert_with(HeaderMap::new);
366                if append {
367                    headers.append(key, value);
368                } else {
369                    headers.insert(key, value);
370                }
371            }
372            Err(e) => self.error = Some(e),
373        }
374        self
375    }
376}
377
378impl<T: Responder<St>, St: State> Responder<St> for CustomResponder<T, St> {
379    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response {
380        if let Some(err) = self.error {
381            return Response::from(err);
382        }
383        let mut res = self.responder.respond_to(st, req).await;
384
385        if let Some(status) = self.status {
386            *res.status_mut() = status;
387        }
388        if let Some(headers) = self.headers {
389            for key in headers.keys() {
390                res.headers_mut().remove(key);
391            }
392            for (k, v) in &headers {
393                res.headers_mut().append(k.clone(), v.clone());
394            }
395        }
396        res
397    }
398}
399
400/// Combines two different responder types into a single type
401///
402/// ```rust
403/// use ntex::{web::HttpResponse, util::Either};
404///
405/// fn index() -> Either<HttpResponse, &'static str> {
406///     if is_a_variant() {
407///         // <- choose left variant
408///         Either::Left(HttpResponse::BadRequest().body("Bad data"))
409///     } else {
410///         // <- Right variant
411///         Either::Right("Hello!")
412///     }
413/// }
414/// # fn is_a_variant() -> bool { true }
415/// # fn main() {}
416/// ```
417impl<St, A, B> Responder<St> for Either<A, B>
418where
419    St: State,
420    A: Responder<St>,
421    B: Responder<St>,
422{
423    async fn respond_to(self, st: &St, req: &HttpRequest) -> Response {
424        match self {
425            Either::Left(a) => a.respond_to(st, req).await,
426            Either::Right(b) => b.respond_to(st, req).await,
427        }
428    }
429}
430
431impl<St, T> Responder<St> for InternalError<T>
432where
433    St: State,
434    T: std::fmt::Debug + std::fmt::Display + 'static,
435{
436    async fn respond_to(self, st: &St, _: &HttpRequest) -> Response {
437        WebResponseError::<St, St::Error>::error_response(&self, st)
438    }
439}
440
441#[cfg(test)]
442pub(crate) mod tests {
443    use super::*;
444    use crate::http::Response as HttpResponse;
445    use crate::http::body::{Body, ResponseBody};
446    use crate::http::header::CONTENT_TYPE;
447    use crate::web;
448    use crate::web::test::{TestRequest, init_service};
449
450    fn responder<T: Responder>(responder: T) -> impl Responder {
451        responder
452    }
453
454    /// STATEMENT: `Either` responders render the selected branch's response type.
455    ///
456    /// HOW:
457    /// - Return a bad-request builder for an empty query and a string for a nonempty query.
458    /// - Request both variants and assert 400 and OK, respectively.
459    #[crate::rt_test]
460    async fn test_either_responder() {
461        let srv = init_service(web::App::new().service(web::resource("/index.html").to(
462            async move |req: HttpRequest| {
463                if req.query_string().is_empty() {
464                    Either::Left(HttpResponse::BadRequest())
465                } else {
466                    Either::Right("hello")
467                }
468            },
469        )))
470        .await;
471
472        let req = TestRequest::with_uri("/index.html").to_request();
473        let resp = srv.call(req).await.unwrap();
474        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
475
476        let req = TestRequest::with_uri("/index.html?query=test").to_request();
477        let resp = srv.call(req).await.unwrap();
478        assert_eq!(resp.status(), StatusCode::OK);
479    }
480
481    /// STATEMENT: Optional responders map `None` to not found and render the value in `Some`.
482    ///
483    /// HOW:
484    /// - Register handlers returning `None` and `Some("some")`.
485    /// - Assert 404 for the former and OK with the exact byte body for the latter.
486    #[crate::rt_test]
487    async fn test_option_responder() {
488        let srv = init_service(
489            web::App::new()
490                .service(web::resource("/none").to(async || Option::<&'static str>::None))
491                .service(web::resource("/some").to(async || Some("some"))),
492        )
493        .await;
494
495        let req = TestRequest::with_uri("/none").to_request();
496        let resp = srv.call(req).await.unwrap();
497        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
498
499        let req = TestRequest::with_uri("/some").to_request();
500        let resp = srv.call(req).await.unwrap();
501        assert_eq!(resp.status(), StatusCode::OK);
502        if let ResponseBody::Body(Body::Bytes(b)) = resp.body() {
503            let bytes: Bytes = b.clone();
504            assert_eq!(bytes, Bytes::from_static(b"some"));
505        } else {
506            panic!()
507        }
508    }
509
510    /// STATEMENT: Text and binary responders preserve bytes and select their corresponding content type.
511    ///
512    /// HOW:
513    /// - Render string, borrowed string, byte slice, `Bytes`, and `BytesMut` values.
514    /// - Assert OK, unchanged bytes, and textual or octet-stream content types as appropriate.
515    /// - Render an `InternalError` and assert its explicit bad-request status.
516    #[crate::rt_test]
517    async fn test_responder() {
518        let req = TestRequest::default().to_http_request();
519
520        let resp: HttpResponse = responder("test").respond_to(&(), &req).await;
521        assert_eq!(resp.status(), StatusCode::OK);
522        assert_eq!(resp.get_body_ref(), b"test");
523        assert_eq!(
524            resp.headers().get(CONTENT_TYPE).unwrap(),
525            HeaderValue::from_static("text/plain; charset=utf-8")
526        );
527
528        let resp: HttpResponse = responder(&b"test"[..]).respond_to(&(), &req).await;
529        assert_eq!(resp.status(), StatusCode::OK);
530        assert_eq!(resp.get_body_ref(), b"test");
531        assert_eq!(
532            resp.headers().get(CONTENT_TYPE).unwrap(),
533            HeaderValue::from_static("application/octet-stream")
534        );
535
536        let resp: HttpResponse = responder("test".to_string()).respond_to(&(), &req).await;
537        assert_eq!(resp.status(), StatusCode::OK);
538        assert_eq!(resp.get_body_ref(), b"test");
539        assert_eq!(
540            resp.headers().get(CONTENT_TYPE).unwrap(),
541            HeaderValue::from_static("text/plain; charset=utf-8")
542        );
543
544        let resp: HttpResponse = responder(&"test".to_string()).respond_to(&(), &req).await;
545        assert_eq!(resp.status(), StatusCode::OK);
546        assert_eq!(resp.get_body_ref(), b"test");
547        assert_eq!(
548            resp.headers().get(CONTENT_TYPE).unwrap(),
549            HeaderValue::from_static("text/plain; charset=utf-8")
550        );
551
552        let resp: HttpResponse = responder(Bytes::from_static(b"test"))
553            .respond_to(&(), &req)
554            .await;
555        assert_eq!(resp.status(), StatusCode::OK);
556        assert_eq!(resp.get_body_ref(), b"test");
557        assert_eq!(
558            resp.headers().get(CONTENT_TYPE).unwrap(),
559            HeaderValue::from_static("application/octet-stream")
560        );
561
562        let resp: HttpResponse = responder(BytesMut::from(b"test".as_ref()))
563            .respond_to(&(), &req)
564            .await;
565        assert_eq!(resp.status(), StatusCode::OK);
566        assert_eq!(resp.get_body_ref(), b"test");
567        assert_eq!(
568            resp.headers().get(CONTENT_TYPE).unwrap(),
569            HeaderValue::from_static("application/octet-stream")
570        );
571
572        // InternalError
573        let resp: HttpResponse = responder(InternalError::new("err", StatusCode::BAD_REQUEST))
574            .respond_to(&(), &req)
575            .await;
576        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
577    }
578
579    /// STATEMENT: Result responders render successful values and delegate failures to error rendering.
580    ///
581    /// HOW:
582    /// - Render an OK string result and assert OK, its bytes, and the text content type.
583    /// - Render an `InternalError` result and assert `BAD_REQUEST`.
584    #[crate::rt_test]
585    async fn test_result_responder() {
586        let req = TestRequest::default().to_http_request();
587
588        // Result<I, E>
589        let resp: HttpResponse = Responder::<()>::respond_to(
590            Ok::<String, std::convert::Infallible>("test".to_string()),
591            &(),
592            &req,
593        )
594        .await;
595        assert_eq!(resp.status(), StatusCode::OK);
596        assert_eq!(resp.get_body_ref(), b"test");
597        assert_eq!(
598            resp.headers().get(CONTENT_TYPE).unwrap(),
599            HeaderValue::from_static("text/plain; charset=utf-8")
600        );
601
602        let res = responder(Err::<String, _>(InternalError::new(
603            "err",
604            StatusCode::BAD_REQUEST,
605        )))
606        .respond_to(&(), &req)
607        .await;
608        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
609    }
610
611    /// STATEMENT: Responder customization overrides status or headers without changing body bytes.
612    ///
613    /// HOW:
614    /// - Apply `with_status` to a string responder and assert 400 with the original body.
615    /// - Apply `with_header` and assert OK, the original body, and the replacement content type.
616    #[crate::rt_test]
617    async fn test_custom_responder() {
618        let req = TestRequest::default().to_http_request();
619        let res = responder("test".to_string())
620            .with_status(StatusCode::BAD_REQUEST)
621            .respond_to(&(), &req)
622            .await;
623        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
624        assert_eq!(res.get_body_ref(), b"test");
625
626        let res = responder("test".to_string())
627            .with_header("content-type", "json")
628            .respond_to(&(), &req)
629            .await;
630
631        assert_eq!(res.status(), StatusCode::OK);
632        assert_eq!(res.get_body_ref(), b"test");
633        assert_eq!(
634            res.headers().get(CONTENT_TYPE).unwrap(),
635            HeaderValue::from_static("json")
636        );
637    }
638
639    /// STATEMENT: `with_header` keeps every value, `set_header` replaces them, both replace original values, and invalid syntax is rejected.
640    ///
641    /// HOW:
642    /// - Add `x-test` three times with `with_header` and assert all values are kept in order.
643    /// - Add two values then `set_header`, and `set_header` then `with_header`, asserting the replaced and appended values.
644    /// - Replace multiple original content types with `with_header` and with `set_header`, asserting only the custom value remains.
645    /// - Supply an invalid name and a newline-containing value (also via `set_header`) and assert 500 responses.
646    /// - Assert the invalid value is absent even when a successful status override was requested.
647    #[crate::rt_test]
648    async fn test_custom_responder_headers() {
649        let req = TestRequest::default().to_http_request();
650        let res = responder("test".to_string())
651            .with_header("x-test", "1")
652            .with_header("x-test", "2")
653            .with_header("x-test", "3")
654            .respond_to(&(), &req)
655            .await;
656        assert_eq!(res.status(), StatusCode::OK);
657        let values: Vec<_> = res.headers().get_all("x-test").collect();
658        assert_eq!(
659            values,
660            [
661                HeaderValue::from_static("1"),
662                HeaderValue::from_static("2"),
663                HeaderValue::from_static("3")
664            ]
665        );
666
667        let res = responder("test".to_string())
668            .with_header("x-test", "1")
669            .with_header("x-test", "2")
670            .set_header("x-test", "3")
671            .respond_to(&(), &req)
672            .await;
673        let values: Vec<_> = res.headers().get_all("x-test").collect();
674        assert_eq!(values, [HeaderValue::from_static("3")]);
675
676        let res = CustomResponder::<_, ()>::new(responder("test".to_string()))
677            .set_header("x-test", "1")
678            .set_header("x-test", "2")
679            .with_header("x-test", "3")
680            .respond_to(&(), &req)
681            .await;
682        let values: Vec<_> = res.headers().get_all("x-test").collect();
683        assert_eq!(
684            values,
685            [HeaderValue::from_static("2"), HeaderValue::from_static("3")]
686        );
687
688        // header set by the responder is replaced
689        let original = || {
690            responder(
691                HttpResponse::Ok()
692                    .header(CONTENT_TYPE, "text/plain")
693                    .header(CONTENT_TYPE, "text/html")
694                    .build(),
695            )
696        };
697        let res = original()
698            .with_header(CONTENT_TYPE, "json")
699            .respond_to(&(), &req)
700            .await;
701        let values: Vec<_> = res.headers().get_all(CONTENT_TYPE).collect();
702        assert_eq!(values, [HeaderValue::from_static("json")]);
703
704        let res = CustomResponder::<_, ()>::new(original())
705            .set_header(CONTENT_TYPE, "json")
706            .respond_to(&(), &req)
707            .await;
708        let values: Vec<_> = res.headers().get_all(CONTENT_TYPE).collect();
709        assert_eq!(values, [HeaderValue::from_static("json")]);
710
711        let res = responder("test".to_string())
712            .with_header("bad header", "1")
713            .respond_to(&(), &req)
714            .await;
715        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
716
717        let res = CustomResponder::<_, ()>::new(responder("test".to_string()))
718            .set_header("x-test", "bad\nvalue")
719            .respond_to(&(), &req)
720            .await;
721        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
722
723        let res = responder("test".to_string())
724            .with_header("x-test", "bad\nvalue")
725            .with_status(StatusCode::CREATED)
726            .respond_to(&(), &req)
727            .await;
728        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
729        assert!(res.headers().get("x-test").is_none());
730    }
731
732    /// STATEMENT: Tuple responders apply their status and support additional header customization.
733    ///
734    /// HOW:
735    /// - Render a string/status tuple and assert the chosen status and original bytes.
736    /// - Wrap an OK tuple in `CustomResponder`, override content type, and assert status, body, and header.
737    #[crate::rt_test]
738    async fn test_tuple_responder_with_status_code() {
739        let req = TestRequest::default().to_http_request();
740        let res =
741            Responder::<()>::respond_to(("test".to_string(), StatusCode::BAD_REQUEST), &(), &req)
742                .await;
743        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
744        assert_eq!(res.get_body_ref(), b"test");
745
746        let req = TestRequest::default().to_http_request();
747        let res = CustomResponder::<_, ()>::new(("test".to_string(), StatusCode::OK))
748            .with_header("content-type", "json")
749            .respond_to(&(), &req)
750            .await;
751        assert_eq!(res.status(), StatusCode::OK);
752        assert_eq!(res.get_body_ref(), b"test");
753        assert_eq!(
754            res.headers().get(CONTENT_TYPE).unwrap(),
755            HeaderValue::from_static("json")
756        );
757    }
758
759    /// STATEMENT: Status overrides on a `Result` replace error statuses, while mapping only the `Ok` value preserves them.
760    ///
761    /// HOW:
762    /// - Render a `400 Bad Request` `Err` through `with_status(CREATED)` and a `(result, CREATED)` tuple and assert both send `201` with the error body.
763    /// - Render the same `Err` through `Result::map` with `with_status(CREATED)` and with a tuple, and assert both keep `400`.
764    /// - Render an `Ok` value through both mapped forms and assert they send `201` with the success body.
765    #[crate::rt_test]
766    async fn test_result_status_override_and_success_only_mapping() {
767        let req = TestRequest::default().to_http_request();
768        let err = || Err::<&'static str, _>(crate::web::error::ErrorBadRequest("invalid"));
769
770        for res in [
771            err()
772                .with_status(StatusCode::CREATED)
773                .respond_to(&(), &req)
774                .await,
775            (err(), StatusCode::CREATED).respond_to(&(), &req).await,
776        ] {
777            assert_eq!(res.status(), StatusCode::CREATED);
778            assert_eq!(res.get_body_ref(), b"invalid");
779        }
780
781        for res in [
782            err()
783                .map(|v| v.with_status(StatusCode::CREATED))
784                .respond_to(&(), &req)
785                .await,
786            err()
787                .map(|v| (v, StatusCode::CREATED))
788                .respond_to(&(), &req)
789                .await,
790        ] {
791            assert_eq!(res.status(), StatusCode::BAD_REQUEST);
792            assert_eq!(res.get_body_ref(), b"invalid");
793        }
794
795        let ok = || Ok::<_, crate::web::error::InternalError<&'static str>>("created");
796        for res in [
797            ok().map(|v| v.with_status(StatusCode::CREATED))
798                .respond_to(&(), &req)
799                .await,
800            ok().map(|v| (v, StatusCode::CREATED))
801                .respond_to(&(), &req)
802                .await,
803        ] {
804            assert_eq!(res.status(), StatusCode::CREATED);
805            assert_eq!(res.get_body_ref(), b"created");
806        }
807    }
808}