How to do it...

Follow the given steps to implement this recipe:

  1. Open the main.rs file in the src directory in your preferred text editor.
  2. Write the code header with the relevant information:
        //-- #########################
//-- Task: Json handling in nickel
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 20 April 17
//-- #########################
  1. 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};
  1. Define a custom Struct type named Person:
        #[derive(RustcDecodable, RustcEncodable)]
struct Person {
firstname: String,
lastname: String,
}
  1. 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");
}
  1. 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:


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.128.105