Skip to content

Commit

Permalink
hellper method for json body
Browse files Browse the repository at this point in the history
  • Loading branch information
fafhrd91 committed Nov 27, 2017
1 parent 42716d3 commit b5a4f6f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use route::Frame;


/// Represents various types of http message body.
#[derive(Debug)]
#[derive(Debug, PartialEq)]
pub enum Body {
/// Empty response. `Content-Length` header is set to `0`
Empty,
Expand All @@ -23,7 +23,7 @@ pub enum Body {

/// Represents various types of binary body.
/// `Content-Length` header is set to length of the body.
#[derive(Debug)]
#[derive(Debug, PartialEq)]
pub enum Binary {
/// Bytes body
Bytes(Bytes),
Expand Down
43 changes: 41 additions & 2 deletions src/httpresponse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use std::convert::Into;
use cookie::CookieJar;
use http::{StatusCode, Version, HeaderMap, HttpTryFrom, Error as HttpError};
use http::header::{self, HeaderName, HeaderValue};
use serde_json;
use serde::Serialize;

use Cookie;
use body::Body;
Expand Down Expand Up @@ -400,7 +402,8 @@ impl HttpResponseBuilder {
self
}

/// Set a body
/// Set a body and generate `HttpResponse`.
/// `HttpResponseBuilder` can not be used after this call.
pub fn body<B: Into<Body>>(&mut self, body: B) -> Result<HttpResponse, HttpError> {
let mut parts = self.parts.take().expect("cannot reuse response builder");
if let Some(e) = self.err.take() {
Expand All @@ -425,7 +428,23 @@ impl HttpResponseBuilder {
})
}

/// Set an empty body
/// Set a json body and generate `HttpResponse`
pub fn json<T: Serialize>(&mut self, value: T) -> Result<HttpResponse, Error> {
let body = serde_json::to_string(&value)?;

let contains = if let Some(parts) = parts(&mut self.parts, &self.err) {
parts.headers.contains_key(header::CONTENT_TYPE)
} else {
true
};
if !contains {
self.header(header::CONTENT_TYPE, "application/json");
}

Ok(self.body(body)?)
}

/// Set an empty body and generate `HttpResponse`
pub fn finish(&mut self) -> Result<HttpResponse, HttpError> {
self.body(Body::Empty)
}
Expand All @@ -442,6 +461,7 @@ fn parts<'a>(parts: &'a mut Option<Parts>, err: &Option<HttpError>) -> Option<&'
#[cfg(test)]
mod tests {
use super::*;
use bytes::Bytes;

#[test]
fn test_body() {
Expand Down Expand Up @@ -479,4 +499,23 @@ mod tests {
.content_encoding(ContentEncoding::Br).finish().unwrap();
assert_eq!(*resp.content_encoding(), ContentEncoding::Br);
}

#[test]
fn test_json() {
let resp = HttpResponse::build(StatusCode::OK)
.json(vec!["v1", "v2", "v3"]).unwrap();
let ct = resp.headers().get(header::CONTENT_TYPE).unwrap();
assert_eq!(ct, header::HeaderValue::from_static("application/json"));
assert_eq!(*resp.body(), Body::from(Bytes::from_static(b"[\"v1\",\"v2\",\"v3\"]")));
}

#[test]
fn test_json_ct() {
let resp = HttpResponse::build(StatusCode::OK)
.header(header::CONTENT_TYPE, "text/json")
.json(vec!["v1", "v2", "v3"]).unwrap();
let ct = resp.headers().get(header::CONTENT_TYPE).unwrap();
assert_eq!(ct, header::HeaderValue::from_static("text/json"));
assert_eq!(*resp.body(), Body::from(Bytes::from_static(b"[\"v1\",\"v2\",\"v3\"]")));
}
}

0 comments on commit b5a4f6f

Please sign in to comment.