Follow the given steps to implement this recipe:
- Open the main.rs file in the src directory in your preferred text editor.
- Write the code header with the relevant information:
//-- #########################
//-- Task: Json handling in nickel
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 20 April 17
//-- #########################
- Import the installed nickel and rustc_serialize crates by using the extern keyword:
extern crate rustc_serialize;
#[macro_use] extern crate nickel;
use nickel::{Nickel, HttpRouter, JsonBody};
- Define a custom Struct type named Person:
#[derive(RustcDecodable, RustcEncodable)]
struct Person {
firstname: String,
lastname: String,
}
- Define the main function, where we declare the server instance:
fn main() {
let mut server = Nickel::new();
server.post("/a/post/request", middleware! {
|request,
response|
let person = request.json_as::<Person>().unwrap();
format!("Hello {} {}", person.firstname,
person.lastname)});
server.listen("127.0.0.1:6767");
}
- Save the file and start the server with the following command from the root directory of the project:
cargo run
We will get the following output on the successful execution of our code in the terminal:
Open your terminal and enter the following command to hit the endpoint with curl:
curl -H "Content-Type: application/json" -X POST -d
'{"firstname":"Vigneshwer","lastname":"Dhinakaran"}'
http://127.0.0.1:6767/a/post/request
On successfully hitting the endpoint with the curl command, we will get the following response (highlighted) in the output: