Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(response): add send_json method #390

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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<D>, res: Response<'a, D>) -> MiddlewareResult<'a, D> {
/// let json_data = String::from("Hello!");
/// res.send_json(&json_data)
/// }
/// ```
pub fn send_json<T: Encodable>(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" :)
//
Expand Down