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::{
9    DefaultError, ErrorContainer, ErrorRenderer, InternalError, WebResponseError,
10};
11use super::httprequest::HttpRequest;
12
13#[allow(async_fn_in_trait)]
14/// Trait implemented by types that can be converted to a http response.
15///
16/// Types that implement this trait can be used as the return type of a handler.
17pub trait Responder<Err = DefaultError> {
18    /// Convert itself to http response.
19    async fn respond_to(self, req: &HttpRequest) -> Response;
20
21    /// Override a status code for a Responder.
22    ///
23    /// ```rust
24    /// use ntex::http::StatusCode;
25    /// use ntex::web::{HttpRequest, Responder};
26    ///
27    /// fn index(req: HttpRequest) -> impl Responder {
28    ///     "Welcome!".with_status(StatusCode::OK)
29    /// }
30    /// # fn main() {}
31    /// ```
32    fn with_status(self, status: StatusCode) -> CustomResponder<Self, Err>
33    where
34        Self: Sized,
35    {
36        CustomResponder::new(self).with_status(status)
37    }
38
39    /// Add header to the Responder's response.
40    ///
41    /// ```rust
42    /// use ntex::web::{self, HttpRequest, Responder};
43    /// use serde::Serialize;
44    ///
45    /// #[derive(Serialize)]
46    /// struct MyObj {
47    ///     name: String,
48    /// }
49    ///
50    /// async fn index(req: HttpRequest) -> impl Responder {
51    ///     web::types::Json(
52    ///         MyObj { name: "Name".to_string() }
53    ///     )
54    ///     .with_header("x-version", "1.2.3")
55    /// }
56    /// # fn main() {}
57    /// ```
58    fn with_header<K, V>(self, key: K, value: V) -> CustomResponder<Self, Err>
59    where
60        Self: Sized,
61        HeaderName: TryFrom<K>,
62        HeaderValue: TryFrom<V>,
63        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
64        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
65    {
66        CustomResponder::new(self).with_header(key, value)
67    }
68}
69
70impl<Err: ErrorRenderer> Responder<Err> for Response {
71    #[inline]
72    async fn respond_to(self, _: &HttpRequest) -> Response {
73        self
74    }
75}
76
77impl<Err: ErrorRenderer> Responder<Err> for ResponseBuilder {
78    #[inline]
79    async fn respond_to(mut self, _: &HttpRequest) -> Response {
80        self.finish()
81    }
82}
83
84impl<T, Err> Responder<Err> for Option<T>
85where
86    T: Responder<Err>,
87    Err: ErrorRenderer,
88{
89    async fn respond_to(self, req: &HttpRequest) -> Response {
90        match self {
91            Some(t) => t.respond_to(req).await,
92            None => Response::build(StatusCode::NOT_FOUND).finish(),
93        }
94    }
95}
96
97impl<T, E, Err> Responder<Err> for Result<T, E>
98where
99    T: Responder<Err>,
100    E: Into<Err::Container>,
101    Err: ErrorRenderer,
102{
103    async fn respond_to(self, req: &HttpRequest) -> Response {
104        match self {
105            Ok(val) => val.respond_to(req).await,
106            Err(e) => e.into().error_response(req),
107        }
108    }
109}
110
111impl<T, Err> Responder<Err> for (T, StatusCode)
112where
113    T: Responder<Err>,
114    Err: ErrorRenderer,
115{
116    async fn respond_to(self, req: &HttpRequest) -> Response {
117        let mut res = self.0.respond_to(req).await;
118        *res.status_mut() = self.1;
119        res
120    }
121}
122
123impl<Err: ErrorRenderer> Responder<Err> for &'static str {
124    async fn respond_to(self, _: &HttpRequest) -> Response {
125        Response::build(StatusCode::OK)
126            .content_type("text/plain; charset=utf-8")
127            .body(self)
128    }
129}
130
131impl<Err: ErrorRenderer> Responder<Err> for &'static [u8] {
132    async fn respond_to(self, _: &HttpRequest) -> Response {
133        Response::build(StatusCode::OK)
134            .content_type("application/octet-stream")
135            .body(self)
136    }
137}
138
139impl<Err: ErrorRenderer> Responder<Err> for String {
140    async fn respond_to(self, _: &HttpRequest) -> Response {
141        Response::build(StatusCode::OK)
142            .content_type("text/plain; charset=utf-8")
143            .body(self)
144    }
145}
146
147impl<Err: ErrorRenderer> Responder<Err> for &String {
148    async fn respond_to(self, _: &HttpRequest) -> Response {
149        Response::build(StatusCode::OK)
150            .content_type("text/plain; charset=utf-8")
151            .body(self)
152    }
153}
154
155impl<Err: ErrorRenderer> Responder<Err> for Bytes {
156    async fn respond_to(self, _: &HttpRequest) -> Response {
157        Response::build(StatusCode::OK)
158            .content_type("application/octet-stream")
159            .body(self)
160    }
161}
162
163impl<Err: ErrorRenderer> Responder<Err> for BytesMut {
164    async fn respond_to(self, _: &HttpRequest) -> Response {
165        Response::build(StatusCode::OK)
166            .content_type("application/octet-stream")
167            .body(self)
168    }
169}
170
171/// Allows to override status code and headers for a responder.
172#[derive(derive_more::Debug)]
173#[debug("CustomResponder")]
174pub struct CustomResponder<T: Responder<Err>, Err> {
175    responder: T,
176    status: Option<StatusCode>,
177    headers: Option<HeaderMap>,
178    error: Option<HttpError>,
179    _t: PhantomData<Err>,
180}
181
182impl<T: Responder<Err>, Err> CustomResponder<T, Err> {
183    fn new(responder: T) -> Self {
184        CustomResponder {
185            responder,
186            status: None,
187            headers: None,
188            error: None,
189            _t: PhantomData,
190        }
191    }
192
193    /// Override a status code for the Responder's response.
194    ///
195    /// ```rust
196    /// use ntex::http::StatusCode;
197    /// use ntex::web::{HttpRequest, Responder};
198    ///
199    /// fn index(req: HttpRequest) -> impl Responder {
200    ///     "Welcome!".with_status(StatusCode::OK)
201    /// }
202    /// # fn main() {}
203    /// ```
204    pub fn with_status(mut self, status: StatusCode) -> Self {
205        self.status = Some(status);
206        self
207    }
208
209    /// Add header to the Responder's response.
210    ///
211    /// ```rust
212    /// use ntex::web::{self, HttpRequest, Responder};
213    /// use serde::Serialize;
214    ///
215    /// #[derive(Serialize)]
216    /// struct MyObj {
217    ///     name: String,
218    /// }
219    ///
220    /// fn index(req: HttpRequest) -> impl Responder {
221    ///     web::types::Json(
222    ///         MyObj{name: "Name".to_string()}
223    ///     )
224    ///     .with_header("x-version", "1.2.3")
225    /// }
226    /// # fn main() {}
227    /// ```
228    pub fn with_header<K, V>(mut self, key: K, value: V) -> Self
229    where
230        HeaderName: TryFrom<K>,
231        HeaderValue: TryFrom<V>,
232        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
233        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
234    {
235        if self.headers.is_none() {
236            self.headers = Some(HeaderMap::new());
237        }
238
239        match HeaderName::try_from(key) {
240            Ok(key) => match HeaderValue::try_from(value) {
241                Ok(value) => {
242                    self.headers.as_mut().unwrap().append(key, value);
243                }
244                Err(e) => self.error = Some(e.into()),
245            },
246            Err(e) => self.error = Some(e.into()),
247        }
248        self
249    }
250}
251
252impl<T: Responder<Err>, Err: ErrorRenderer> Responder<Err> for CustomResponder<T, Err> {
253    async fn respond_to(self, req: &HttpRequest) -> Response {
254        let mut res = self.responder.respond_to(req).await;
255
256        if let Some(status) = self.status {
257            *res.status_mut() = status;
258        }
259        if let Some(ref headers) = self.headers {
260            for (k, v) in headers {
261                res.headers_mut().insert(k.clone(), v.clone());
262            }
263        }
264        res
265    }
266}
267
268/// Combines two different responder types into a single type
269///
270/// ```rust
271/// use ntex::{web::HttpResponse, util::Either};
272///
273/// fn index() -> Either<HttpResponse, &'static str> {
274///     if is_a_variant() {
275///         // <- choose left variant
276///         Either::Left(HttpResponse::BadRequest().body("Bad data"))
277///     } else {
278///         // <- Right variant
279///         Either::Right("Hello!")
280///     }
281/// }
282/// # fn is_a_variant() -> bool { true }
283/// # fn main() {}
284/// ```
285impl<A, B, Err> Responder<Err> for Either<A, B>
286where
287    A: Responder<Err>,
288    B: Responder<Err>,
289    Err: ErrorRenderer,
290{
291    async fn respond_to(self, req: &HttpRequest) -> Response {
292        match self {
293            Either::Left(a) => a.respond_to(req).await,
294            Either::Right(b) => b.respond_to(req).await,
295        }
296    }
297}
298
299impl<T, Err> Responder<Err> for InternalError<T, Err>
300where
301    T: std::fmt::Debug + std::fmt::Display + 'static,
302    Err: ErrorRenderer,
303{
304    async fn respond_to(self, req: &HttpRequest) -> Response {
305        self.error_response(req)
306    }
307}
308
309#[cfg(test)]
310pub(crate) mod tests {
311    use super::*;
312    use crate::http::Response as HttpResponse;
313    use crate::http::body::{Body, ResponseBody};
314    use crate::http::header::CONTENT_TYPE;
315    use crate::web;
316    use crate::web::test::{TestRequest, init_service};
317
318    fn responder<T: Responder<DefaultError>>(responder: T) -> impl Responder<DefaultError> {
319        responder
320    }
321
322    #[crate::rt_test]
323    async fn test_either_responder() {
324        let srv = init_service(web::App::new().service(web::resource("/index.html").to(
325            |req: HttpRequest| async move {
326                if req.query_string().is_empty() {
327                    Either::Left(HttpResponse::BadRequest())
328                } else {
329                    Either::Right("hello")
330                }
331            },
332        )))
333        .await;
334
335        let req = TestRequest::with_uri("/index.html").to_request();
336        let resp = srv.call(req).await.unwrap();
337        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
338
339        let req = TestRequest::with_uri("/index.html?query=test").to_request();
340        let resp = srv.call(req).await.unwrap();
341        assert_eq!(resp.status(), StatusCode::OK);
342    }
343
344    #[crate::rt_test]
345    async fn test_option_responder() {
346        let srv = init_service(
347            web::App::new()
348                .service(
349                    web::resource("/none").to(|| async { Option::<&'static str>::None }),
350                )
351                .service(web::resource("/some").to(|| async { Some("some") })),
352        )
353        .await;
354
355        let req = TestRequest::with_uri("/none").to_request();
356        let resp = srv.call(req).await.unwrap();
357        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
358
359        let req = TestRequest::with_uri("/some").to_request();
360        let resp = srv.call(req).await.unwrap();
361        assert_eq!(resp.status(), StatusCode::OK);
362        if let ResponseBody::Body(Body::Bytes(b)) = resp.response().body() {
363            let bytes: Bytes = b.clone();
364            assert_eq!(bytes, Bytes::from_static(b"some"));
365        } else {
366            panic!()
367        }
368    }
369
370    #[crate::rt_test]
371    async fn test_responder() {
372        let req = TestRequest::default().to_http_request();
373
374        let resp: HttpResponse = responder("test").respond_to(&req).await;
375        assert_eq!(resp.status(), StatusCode::OK);
376        assert_eq!(resp.get_body_ref(), b"test");
377        assert_eq!(
378            resp.headers().get(CONTENT_TYPE).unwrap(),
379            HeaderValue::from_static("text/plain; charset=utf-8")
380        );
381
382        let resp: HttpResponse = responder(&b"test"[..]).respond_to(&req).await;
383        assert_eq!(resp.status(), StatusCode::OK);
384        assert_eq!(resp.get_body_ref(), b"test");
385        assert_eq!(
386            resp.headers().get(CONTENT_TYPE).unwrap(),
387            HeaderValue::from_static("application/octet-stream")
388        );
389
390        let resp: HttpResponse = responder("test".to_string()).respond_to(&req).await;
391        assert_eq!(resp.status(), StatusCode::OK);
392        assert_eq!(resp.get_body_ref(), b"test");
393        assert_eq!(
394            resp.headers().get(CONTENT_TYPE).unwrap(),
395            HeaderValue::from_static("text/plain; charset=utf-8")
396        );
397
398        let resp: HttpResponse = responder(&"test".to_string()).respond_to(&req).await;
399        assert_eq!(resp.status(), StatusCode::OK);
400        assert_eq!(resp.get_body_ref(), b"test");
401        assert_eq!(
402            resp.headers().get(CONTENT_TYPE).unwrap(),
403            HeaderValue::from_static("text/plain; charset=utf-8")
404        );
405
406        let resp: HttpResponse = responder(Bytes::from_static(b"test"))
407            .respond_to(&req)
408            .await;
409        assert_eq!(resp.status(), StatusCode::OK);
410        assert_eq!(resp.get_body_ref(), b"test");
411        assert_eq!(
412            resp.headers().get(CONTENT_TYPE).unwrap(),
413            HeaderValue::from_static("application/octet-stream")
414        );
415
416        let resp: HttpResponse = responder(BytesMut::from(b"test".as_ref()))
417            .respond_to(&req)
418            .await;
419        assert_eq!(resp.status(), StatusCode::OK);
420        assert_eq!(resp.get_body_ref(), b"test");
421        assert_eq!(
422            resp.headers().get(CONTENT_TYPE).unwrap(),
423            HeaderValue::from_static("application/octet-stream")
424        );
425
426        // InternalError
427        let resp: HttpResponse =
428            responder(InternalError::new("err", StatusCode::BAD_REQUEST))
429                .respond_to(&req)
430                .await;
431        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
432    }
433
434    #[crate::rt_test]
435    async fn test_result_responder() {
436        let req = TestRequest::default().to_http_request();
437
438        // Result<I, E>
439        let resp: HttpResponse = Responder::<DefaultError>::respond_to(
440            Ok::<String, std::convert::Infallible>("test".to_string()),
441            &req,
442        )
443        .await;
444        assert_eq!(resp.status(), StatusCode::OK);
445        assert_eq!(resp.get_body_ref(), b"test");
446        assert_eq!(
447            resp.headers().get(CONTENT_TYPE).unwrap(),
448            HeaderValue::from_static("text/plain; charset=utf-8")
449        );
450
451        let res = responder(Err::<String, _>(InternalError::new(
452            "err",
453            StatusCode::BAD_REQUEST,
454        )))
455        .respond_to(&req)
456        .await;
457        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
458    }
459
460    #[crate::rt_test]
461    async fn test_custom_responder() {
462        let req = TestRequest::default().to_http_request();
463        let res = responder("test".to_string())
464            .with_status(StatusCode::BAD_REQUEST)
465            .respond_to(&req)
466            .await;
467        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
468        assert_eq!(res.get_body_ref(), b"test");
469
470        let res = responder("test".to_string())
471            .with_header("content-type", "json")
472            .respond_to(&req)
473            .await;
474
475        assert_eq!(res.status(), StatusCode::OK);
476        assert_eq!(res.get_body_ref(), b"test");
477        assert_eq!(
478            res.headers().get(CONTENT_TYPE).unwrap(),
479            HeaderValue::from_static("json")
480        );
481    }
482
483    #[crate::rt_test]
484    async fn test_tuple_responder_with_status_code() {
485        let req = TestRequest::default().to_http_request();
486        let res = Responder::<DefaultError>::respond_to(
487            ("test".to_string(), StatusCode::BAD_REQUEST),
488            &req,
489        )
490        .await;
491        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
492        assert_eq!(res.get_body_ref(), b"test");
493
494        let req = TestRequest::default().to_http_request();
495        let res =
496            CustomResponder::<_, DefaultError>::new(("test".to_string(), StatusCode::OK))
497                .with_header("content-type", "json")
498                .respond_to(&req)
499                .await;
500        assert_eq!(res.status(), StatusCode::OK);
501        assert_eq!(res.get_body_ref(), b"test");
502        assert_eq!(
503            res.headers().get(CONTENT_TYPE).unwrap(),
504            HeaderValue::from_static("json")
505        );
506    }
507}