From cdbf50ec841501bfb6894e9667d57daee1299e49 Mon Sep 17 00:00:00 2001 From: Sarfaraz Nawaz Date: Wed, 18 Sep 2019 17:24:17 +0800 Subject: [PATCH] Add support for serde_json::Value to be passed as argument to ResponseBuilder.body() --- actix-http/src/body.rs | 19 +++++++++++++++++++ actix-http/src/response.rs | 8 ++++++++ 2 files changed, 27 insertions(+) diff --git a/actix-http/src/body.rs b/actix-http/src/body.rs index e728cdb98..b761738e1 100644 --- a/actix-http/src/body.rs +++ b/actix-http/src/body.rs @@ -234,6 +234,12 @@ impl From for Body { } } +impl From for Body { + fn from(v: serde_json::Value) -> Body { + Body::Bytes(v.to_string().into()) + } +} + impl From> for Body where S: Stream + 'static, @@ -548,4 +554,17 @@ mod tests { assert!(format!("{:?}", Body::Empty).contains("Body::Empty")); assert!(format!("{:?}", Body::Bytes(Bytes::from_static(b"1"))).contains("1")); } + + #[test] + fn test_serde_json() { + use serde_json::json; + assert_eq!( + Body::from(serde_json::Value::String("test".into())).size(), + BodySize::Sized(6) + ); + assert_eq!( + Body::from(json!({"test-key":"test-value"})).size(), + BodySize::Sized(25) + ); + } } diff --git a/actix-http/src/response.rs b/actix-http/src/response.rs index 124bf5f92..5b0b3bc87 100644 --- a/actix-http/src/response.rs +++ b/actix-http/src/response.rs @@ -992,6 +992,14 @@ mod tests { assert_eq!(resp.body().get_ref(), b"[\"v1\",\"v2\",\"v3\"]"); } + #[test] + fn test_serde_json_in_body() { + use serde_json::json; + let resp = + Response::build(StatusCode::OK).body(json!({"test-key":"test-value"})); + assert_eq!(resp.body().get_ref(), br#"{"test-key":"test-value"}"#); + } + #[test] fn test_into_response() { let resp: Response = "test".into();