Skip to content

Commit

Permalink
Merge pull request #435 from jolhoeft/serde
Browse files Browse the repository at this point in the history
feat(serde): replace rustc_serialize with serde
  • Loading branch information
jolhoeft authored Jan 15, 2019
2 parents 13dae86 + f17e675 commit 2d0e3d0
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 61 deletions.
22 changes: 13 additions & 9 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]

name = "nickel"
version = "0.10.2"
version = "0.11.0"
authors = [ "Christoph Burgdorf <[email protected]>",
"Kevin Butler <[email protected]>",
"Simon Persson <[email protected]>",
Expand All @@ -19,17 +19,21 @@ autoexamples = false
unstable = ["hyper/nightly", "compiletest_rs"]

[dependencies]
url = "1.0"
time = "0.1"
typemap = "0.3"
plugin = "0.2"
regex = "1.0"
rustc-serialize = "0.3"
log = "0.3"
groupable = "0.2"
mustache = "0.8"
lazy_static = "1.0"
log = "0.3"
modifier = "0.1"
mustache = "0.9"
plugin = "0.2"
regex = "1.0"
serde = "1.0"
serde_json = "1.0"
time = "0.1"
typemap = "0.3"
url = "1.0"

[dev-dependencies]
serde_derive = "1.0"

[dependencies.hyper]
version = "0.10"
Expand Down
30 changes: 15 additions & 15 deletions examples/integration_testing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
#[cfg_attr(not(test), macro_use)]
extern crate nickel;
extern crate hyper;
extern crate rustc_serialize;
extern crate serde;
extern crate serde_json;
extern crate serde_derive;

use nickel::{Nickel, ListeningServer, HttpRouter, JsonBody, Request, Response, MiddlewareResult};
use nickel::status::StatusCode;

use rustc_serialize::json::Json;

use serde_derive::{Serialize, Deserialize};
use std::error::Error as StdError;
use std::{env, str};
use std::sync::atomic::{self, AtomicUsize};
Expand Down Expand Up @@ -83,26 +83,26 @@ where D: Database {
server.get("/users", middleware! { |_, res| <ServerData>
let users = res.data().get_users();

Json::from_str(&format!(r#"{{ "users": {:?} }}"#, users)).unwrap()
serde_json::from_str::<serde_json::Value>(&format!(r#"{{ "users": {:?} }}"#, users)).unwrap()
});

// Json example
server.post("/", middleware! { |req, res|
#[derive(RustcEncodable, RustcDecodable)]
#[derive(Serialize, Deserialize)]
struct Data { name: String, age: Option<u32> }

let client = try_with!(res, req.json_as::<Data>().map_err(|e| (StatusCode::BadRequest, e)));

match client.age {
Some(age) => {
Json::from_str(&format!(
serde_json::from_str::<serde_json::Value>(&format!(
r#"{{ "message": "Hello {}, your age is {}" }}"#,
client.name,
age
)).unwrap()
}
None => {
Json::from_str(&format!(
serde_json::from_str::<serde_json::Value>(&format!(
r#"{{ "message": "Hello {}, I don't know your age" }}"#,
client.name
)).unwrap()
Expand All @@ -124,7 +124,7 @@ mod tests {

use hyper::header;
use nickel::status::StatusCode;
use rustc_serialize::json::Json;
use serde_json::Value;

use std::{thread, time};

Expand Down Expand Up @@ -154,9 +154,9 @@ mod tests {
fn root_responds_with_modified_json() {
let mut response = post("/", r#"{ "name": "Rust", "age": 1 }"#);

let json = Json::from_str(&response.body()).unwrap();
let json: Value = serde_json::from_str(&response.body()).unwrap();

assert_eq!(json["message"].as_string(), Some("Hello Rust, your age is 1"));
assert_eq!(json["message"].as_str(), Some("Hello Rust, your age is 1"));
assert_eq!(response.status, StatusCode::Ok);
assert_eq!(
response.headers.get::<header::ContentType>(),
Expand All @@ -168,9 +168,9 @@ mod tests {
fn accepts_json_with_missing_fields() {
let mut response = post("/", r#"{ "name": "Rust" }"#);

let json = Json::from_str(&response.body()).unwrap();
let json: Value = serde_json::from_str(&response.body()).unwrap();

assert_eq!(json["message"].as_string(), Some("Hello Rust, I don't know your age"));
assert_eq!(json["message"].as_str(), Some("Hello Rust, I don't know your age"));
assert_eq!(response.status, StatusCode::Ok);
assert_eq!(
response.headers.get::<header::ContentType>(),
Expand Down Expand Up @@ -199,7 +199,7 @@ mod tests {
fn has_no_users_by_default() {
let mut response = get("/users");

let json = Json::from_str(&response.body()).unwrap();
let json: Value = serde_json::from_str(&response.body()).unwrap();

assert_eq!(json["users"].as_array().unwrap().len(), 0);
assert_eq!(response.status, StatusCode::Ok);
Expand All @@ -219,7 +219,7 @@ mod tests {

let mut response = server.get("/users");

let json = Json::from_str(&response.body()).unwrap();
let json: Value = serde_json::from_str(&response.body()).unwrap();

assert_eq!(json["users"].as_array().unwrap().len(), 3);
assert_eq!(response.status, StatusCode::Ok);
Expand Down
21 changes: 6 additions & 15 deletions examples/json.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,22 @@
#[macro_use] extern crate nickel;
extern crate rustc_serialize;
extern crate serde;
extern crate serde_json;
#[macro_use] extern crate serde_derive;

use std::collections::BTreeMap;
use nickel::status::StatusCode;
use nickel::{Nickel, JsonBody, HttpRouter, MediaType};
use rustc_serialize::json::{Json, ToJson};

#[derive(RustcDecodable, RustcEncodable)]
#[derive(Serialize, Deserialize)]
struct Person {
first_name: String,
last_name: String,
}

impl ToJson for Person {
fn to_json(&self) -> Json {
let mut map = BTreeMap::new();
map.insert("first_name".to_string(), self.first_name.to_json());
map.insert("last_name".to_string(), self.last_name.to_json());
Json::Object(map)
}
}

fn main() {
let mut server = Nickel::new();

// try it with curl
// curl 'http://localhost:6767/a/post/request' -H 'Content-Type: application/json;charset=UTF-8' --data-binary $'{ "firstname": "John","lastname": "Connor" }'
// curl 'http://localhost:6767/a/post/request' -H 'Content-Type: application/json;charset=UTF-8' --data-binary $'{ "first_name": "John","last_name": "Connor" }'
server.post("/", middleware! { |request, response|
let person = try_with!(response, {
request.json_as::<Person>().map_err(|e| (StatusCode::BadRequest, e))
Expand All @@ -43,7 +34,7 @@ fn main() {
first_name: first_name.to_string(),
last_name: last_name.to_string(),
};
person.to_json()
serde_json::to_value(person).map_err(|e| (StatusCode::InternalServerError, e))
});

// go to http://localhost:6767/content-type to see this route in action
Expand Down
5 changes: 3 additions & 2 deletions examples/macro_example.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#[macro_use] extern crate nickel;
extern crate regex;
extern crate rustc_serialize;
extern crate serde;
#[macro_use] extern crate serde_derive;
extern crate hyper;

use std::io::Write;
Expand All @@ -12,7 +13,7 @@ use nickel::{
use regex::Regex;
use hyper::header::Location;

#[derive(RustcDecodable, RustcEncodable)]
#[derive(Serialize, Deserialize)]
struct Person {
firstname: String,
lastname: String,
Expand Down
9 changes: 5 additions & 4 deletions src/body_parser.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use hyper::header::ContentType;
use hyper::mime::{Mime, SubLevel, TopLevel};
use serialize::{Decodable, json};
use serde::Deserialize;
use serde_json;
use request::Request;
use plugin::{Plugin, Pluggable};
use status::StatusCode;
Expand Down Expand Up @@ -75,16 +76,16 @@ impl<'mw, 'conn, D> FormBody for Request<'mw, 'conn, D> {
}

pub trait JsonBody {
fn json_as<T: Decodable>(&mut self) -> Result<T, io::Error>;
fn json_as<'a, T: Deserialize<'a>>(&'a mut self) -> Result<T, io::Error>;
}

impl<'mw, 'conn, D> JsonBody for Request<'mw, 'conn, D> {
// FIXME: Update the error type.
// Would be good to capture parsing error rather than a generic io::Error.
// FIXME: Do the content-type check
fn json_as<T: Decodable>(&mut self) -> Result<T, io::Error> {
fn json_as<'a, T: Deserialize<'a>>(&'a mut self) -> Result<T, io::Error> {
self.get_ref::<BodyReader>().and_then(|body|
json::decode::<T>(&*body).map_err(|err|
serde_json::from_str::<T>(&*body).map_err(|err|
io::Error::new(ErrorKind::Other, format!("Parse error: {}", err))
)
)
Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#![doc(test(attr(deny(warnings))))]

extern crate time;
extern crate rustc_serialize as serialize;
extern crate serde;
extern crate serde_json;
pub extern crate hyper;
extern crate regex;
extern crate typemap;
Expand Down
6 changes: 3 additions & 3 deletions src/responder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
use {Response, NickelError, MiddlewareResult, Halt};
use hyper::status::{StatusCode, StatusClass};
use hyper::header;
use serialize::json;
use serde_json;
use mimes::MediaType;
use std::io::Write;

Expand All @@ -31,10 +31,10 @@ impl<D> Responder<D> for () {
}
}

impl<D> Responder<D> for json::Json {
impl<D> Responder<D> for serde_json::Value {
fn respond<'a>(self, mut res: Response<'a, D>) -> MiddlewareResult<'a, D> {
maybe_set_type(&mut res, MediaType::Json);
res.send(json::encode(&self)
res.send(serde_json::to_string(&self)
.map_err(|e| format!("Failed to parse JSON: {}", e)))
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/response.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::mem;
use std::borrow::Cow;
use std::path::Path;
use serialize::Encodable;
use serde::Serialize;
use hyper::status::StatusCode;
use hyper::server::Response as HyperResponse;
use hyper::header::{
Expand Down Expand Up @@ -206,7 +206,7 @@ impl<'a, D> Response<'a, D, Fresh> {
/// }
/// ```
pub fn render<T, P>(self, path: P, data: &T) -> MiddlewareResult<'a, D>
where T: Encodable, P: AsRef<Path> + Into<String> {
where T: Serialize, P: AsRef<Path> + Into<String> {

let mut self_started = self.start()?;
match self_started.templates.render(path, &mut self_started, data) {
Expand Down
10 changes: 5 additions & 5 deletions src/template_cache.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use mustache::{Error, Template, compile_path};
use serialize::Encodable;
use serde::Serialize;
use std::collections::HashMap;
use std::fs::metadata;
use std::io::Write;
Expand All @@ -25,7 +25,7 @@ impl TemplateEntry {

// render the tempate with the given data
fn render<W, D>(&self, writer: &mut W, data: &D) -> Result<(), Error>
where W: Write, D: Encodable {
where W: Write, D: Serialize {
self.template.render(writer, data)
}
}
Expand Down Expand Up @@ -85,7 +85,7 @@ impl TemplateCache {
//
// * Err(e) - mustache error
fn try_render_template<P, W, D>(&self, path: P, writer: &mut W, data: &D) -> Result<bool, Error>
where P: AsRef<Path>, W: Write, D: Encodable {
where P: AsRef<Path>, W: Write, D: Serialize {

let c = self.cache.read().expect("TemplateCache::try_render_template - cache poisoned");
if let Some(template) = c.get(&path.as_ref().to_path_buf()) {
Expand Down Expand Up @@ -118,7 +118,7 @@ impl TemplateCache {
// Load the template from disk, compile it, store the compiled
// template in cache, and render. This needs a write lock.
fn load_render_template<P, W, D>(&self, path: P, writer: &mut W, data: &D) -> Result<(), Error>
where P: AsRef<Path>, W: Write, D: Encodable {
where P: AsRef<Path>, W: Write, D: Serialize {

let mut c = self.cache.write().expect("TemplateCache::load_render_template - cache poisoned");
let template = TemplateEntry::from_template_file(&path)?;
Expand All @@ -131,7 +131,7 @@ impl TemplateCache {
/// `data`. Templates will be reloaded if necessary according to
/// the reload policy.
pub fn render<P, W, D>(&self, path: P, writer: &mut W, data: &D) -> Result<(), Error>
where P: AsRef<Path>, W: Write, D: Encodable {
where P: AsRef<Path>, W: Write, D: Serialize {
let rendered = match self.try_render_template(&path, writer, data) {
Ok(r) => r,
Err(e) => {
Expand Down
4 changes: 3 additions & 1 deletion tests/example_tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
extern crate rustc_serialize;
extern crate serde;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate hyper;
// HACK: integration_testing example refers to `nickel::foo`
// and this import helps that resolve rather than requiring `self::nickel::foo`
Expand Down
8 changes: 4 additions & 4 deletions tests/examples/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ mod outgoing {
use super::super::with_path;
use util::*;

use rustc_serialize::json;
use serde_json;

use std::collections::HashMap;
use hyper::{mime, header};
Expand All @@ -57,7 +57,7 @@ mod outgoing {
fn serializes_valid_json() {
with_path("/Pea/Nut", |res| {
let s = read_body_to_string(res);
let map: HashMap<String, String> = json::decode(&s).unwrap();
let map: HashMap<String, String> = serde_json::from_str(&s).unwrap();
assert_eq!(map["first_name"], "Pea");
assert_eq!(map["last_name"], "Nut");
})
Expand All @@ -77,7 +77,7 @@ mod outgoing {
use super::super::with_path;
use util::*;

use rustc_serialize::json;
use serde_json;

use std::collections::HashMap;
use hyper::{mime, header};
Expand All @@ -86,7 +86,7 @@ mod outgoing {
fn serializes_valid_json() {
with_path("/raw", |res| {
let s = read_body_to_string(res);
let map: HashMap<String, String> = json::decode(&s).unwrap();
let map: HashMap<String, String> = serde_json::from_str(&s).unwrap();
assert_eq!(map["foo"], "bar");
})
}
Expand Down

0 comments on commit 2d0e3d0

Please sign in to comment.