From bc1c2b889bd39c7fc329e668ccf1e73c740f7355 Mon Sep 17 00:00:00 2001 From: Kilte Leichnam Date: Fri, 9 Dec 2016 10:03:04 +0300 Subject: [PATCH] feat(response): add send_json method --- src/response.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/response.rs b/src/response.rs index 462e11172b..968af8f39c 100644 --- a/src/response.rs +++ b/src/response.rs @@ -4,7 +4,7 @@ use std::sync::RwLock; use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::path::Path; -use serialize::Encodable; +use serialize::{Encodable, json}; use hyper::status::StatusCode; use hyper::server::Response as HyperResponse; use hyper::header::{ @@ -146,6 +146,24 @@ impl<'a, D> Response<'a, D, Fresh> { } } + /// Writes a JSON to the output + /// + /// # Examples + /// ```{rust} + /// use nickel::{Request, Response, MiddlewareResult}; + /// + /// # #[allow(dead_code)] + /// fn handler<'a, D>(_: &mut Request, res: Response<'a, D>) -> MiddlewareResult<'a, D> { + /// let json_data = String::from("Hello!"); + /// res.send_json(&json_data) + /// } + /// ``` + pub fn send_json(mut self, data: &T) -> MiddlewareResult<'a, D> { + let encoded = try_with!(self, json::encode(data).map_err(|e| (StatusCode::InternalServerError, e))); + self.set(MediaType::Json); + self.send(encoded) + } + // TODO: This needs to be more sophisticated to return the correct headers // not just "some headers" :) //