Skip to content

Instantly share code, notes, and snippets.

@Ryman
Created October 24, 2015 15:22
Show Gist options
  • Select an option

  • Save Ryman/fe37eb38f218e6131d2c to your computer and use it in GitHub Desktop.

Select an option

Save Ryman/fe37eb38f218e6131d2c to your computer and use it in GitHub Desktop.
Nickel json for custom types example
#[macro_use] extern crate nickel;
extern crate rustc_serialize;
use nickel::{Nickel, MediaType};
use rustc_serialize::json;
#[derive(RustcEncodable)]
struct Fruit<'a> {
name: &'a str
}
fn main(){
let mut server = Nickel::new();
server.utilize(router! {
get "/:title" => |_req, mut res| {
let _title = _req.param("title").unwrap();
let fruit1 = Fruit { name: "dekopon orange "};
let fruit2 = Fruit { name: "fuji apple"};
let fruit3 = Fruit { name: "palmer mango"};
let fruit4 = Fruit { name: "italy grapes"};
let basket = vec!(fruit1, fruit2, fruit3, fruit4);
// If you want to use to_json, you'll need to implement `rustc_serialize::json::ToJson`
// alternatively, you can just derive `RustcEncodable` and use `json::encode(..)` as below
// res.set(MediaType::Json);
// json::encode(&basket).unwrap()
// if you want to do something a bit more complicated, you can use a viewmodel
#[derive(RustcEncodable)]
struct ViewModel<'a> {
title: &'a str,
basket: &'a [Fruit<'a>]
}
let viewmodel = ViewModel {
title: _title,
basket: &basket
};
res.set(MediaType::Json);
json::encode(&viewmodel).unwrap()
}
});
server.listen("127.0.0.1:6767");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment