From b1143168e53a65824b23b6cfff6d2db7921846ef Mon Sep 17 00:00:00 2001 From: messense Date: Thu, 11 Jul 2019 16:42:58 +0800 Subject: [PATCH] Impl Responder for (T, StatusCode) where T: Responder (#954) --- CHANGES.md | 4 ++++ src/responder.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 641e09bd..0b3f3e0c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,10 @@ ## [1.0.4] - TBD +### Added + +* Add `Responder` impl for `(T, StatusCode) where T: Responder` + ### Changed * Upgrade `rand` dependency version to 0.7 diff --git a/src/responder.rs b/src/responder.rs index 47a8800e..6bd25e6e 100644 --- a/src/responder.rs +++ b/src/responder.rs @@ -137,6 +137,22 @@ impl Responder for () { } } +impl Responder for (T, StatusCode) +where + T: Responder, +{ + type Error = T::Error; + type Future = CustomResponderFut; + + fn respond_to(self, req: &HttpRequest) -> Self::Future { + CustomResponderFut { + fut: self.0.respond_to(req).into_future(), + status: Some(self.1), + headers: None, + } + } +} + impl Responder for &'static str { type Error = Error; type Future = FutureResult; @@ -624,4 +640,29 @@ pub(crate) mod tests { HeaderValue::from_static("json") ); } + + #[test] + fn test_tuple_responder_with_status_code() { + let req = TestRequest::default().to_http_request(); + let res = block_on( + ("test".to_string(), StatusCode::BAD_REQUEST).respond_to(&req) + ) + .unwrap(); + assert_eq!(res.status(), StatusCode::BAD_REQUEST); + assert_eq!(res.body().bin_ref(), b"test"); + + let req = TestRequest::default().to_http_request(); + let res = block_on( + ("test".to_string(), StatusCode::OK) + .with_header("content-type", "json") + .respond_to(&req) + ) + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + assert_eq!(res.body().bin_ref(), b"test"); + assert_eq!( + res.headers().get(CONTENT_TYPE).unwrap(), + HeaderValue::from_static("json") + ); + } }