The serde crate

When I started to use Rust in my projects, I used to use the popular rustc_serialize crate. This wasn't bad, but I found that it wasn't flexible enough. For example, I couldn't use generic data types in my own structs. The serde crate was created to eliminate the shortcomings of the rustc_serialize crate. serde has been the main crate for serialization and deserialization in Rust since the serde crate reached the 1.0 release branch.

We used this crate in the previous chapter to deserialize a configuration file. We're now going to use it to transform request and response data to text or binary data.

To explore serialization, we'll use a microservice that generates random numbers. We'll rewrite a very simple version without logging, reading arguments, environment variables, or configuration files. It will use the HTTP body to specify a range of random values and a random distribution to generate a number from.

Our service will handle requests for the /random path only. It will expect both a request and a response in JSON format. As mentioned, the serde crate provides serialization capabilities to the code. We also need the serde_derive crate to derive the serialization method automatically. The serde crate contains only core types and traits to make the serialization process universal and reusable, but specific formats are implemented in other crates. We'll use serde_json, which provides a serializer in JSON format.

Copy the code of the minimal random-number-generating service and add these dependencies to Cargo.toml:

[dependencies]
futures = "0.1"
hyper = "0.12"
rand = "0.5"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"

Import these crates into the main.rs source file:

extern crate futures;
extern crate hyper;
extern crate rand;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

As you can see, we imported a macro from the serde_derive and serde_json crates to use a JSON serializer. We don't import the serde crate, because we won't use it directly, but it's necessary to use the macro. We can now look at the different parts of the code. At first, we'll examine the request and response types. After that, we'll implement a handler to use it.

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

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