Different formats

We need two extra crates: queryst for parsing parameters from the query string, and the serde_cbor crate to support the CBOR serialization format. Add these to your Cargo.toml:

queryst = "2.0"
serde_cbor = "0.8"

Also, import them in main.rs:

extern crate queryst;
extern crate serde_cbor;

Instead of using serde_json::to_string directly in the handler, we'll move it to a separate function that serializes data depending on the expected format:

fn serialize(format: &str, resp: &RngResponse) -> Result<Vec<u8>, Error> {
match format {
"json" => {
Ok(serde_json::to_vec(resp)?)
},
"cbor" => {
Ok(serde_cbor::to_vec(resp)?)
},
_ => {
Err(format_err!("unsupported format {}", format))
},
}
}

In this code, we used a match expression to detect a format. Significantly, we changed the String result to a binary type, Vec<u8>. We also used failure::Error as an error type, because both serde_json and serde_cbor have their own error types and we can convert them to a generic error using the ? operator.

If the provided format is unknown, we can construct an Error with the format_err! macro of the failure crate. This macro works like the println! function, but it creates a generic error based on a string value.

We also changed the Error type in import section. Previously, it was the hyper::Error type from the hyper crate, but we'll now use the failure::Error type instead and use a crate name prefix for errors.

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

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