Parsing a query

The HTTP URI can contain a query string with parameters that we can use to tune a request. The Request type has a method, uri, which returns a query string if it's available. We added the queryst crate, which parses a query string to serde_json::Value. We'll use this value to extract the "format" parameters from the query string. If the format isn't provided, we'll use "json" as a default value. Add the format-extracting block to the branch that handles requests to the /random path and use the serialize function that we previously declared:

(&Method::POST, "/random") => {
let format = {
let uri = req.uri().query().unwrap_or("");
let query = queryst::parse(uri).unwrap_or(Value::Null);
query["format"].as_str().unwrap_or("json").to_string()
};
let body = req.into_body().concat2()
.map(move |chunks| {
let res = serde_json::from_slice::<RngRequest>(chunks.as_ref())
.map(handle_request)
.map_err(Error::from)
.and_then(move |resp| serialize(&format, &resp));
match res {
Ok(body) => {
Response::new(body.into())
},
Err(err) => {
Response::builder()
.status(StatusCode::UNPROCESSABLE_ENTITY)
.body(err.to_string().into())
.unwrap()
},
}
});
Box::new(body)
},

This code extracts a format value from a query string, processes a request, and returns a serialized value using a chosen format.

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

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