POST requests

For POST requests, we need input parameters that will be serialized to the request's body, and output parameters that will be deserialized from the request's response body. Look at the following function:

fn post_request<T, O>(url: &str, params: T) -> impl Future<Item = O, Error = Error>
where
T: Serialize,
O: for <'de> Deserialize<'de> + 'static,
{
client::ClientRequest::post(url)
.form(params).into_future().and_then(|req| {
req.send()
.map_err(Error::from).and_then(|resp| {
if resp.status().is_success() {
let fut = resp.json::<O>().from_err();
boxed(fut)
} else {
error!("Microservice error: {}", resp.status());
let fut = Err(format_err!("microservice error"))
.into_future().from_err();
boxed(fut)
}
})
})
}

The post_request function creates ClientRequestBuilder with the post method of ClientRequest and fills a form with values from the params variable. We convert Result into Future and send a request to a server. Also, as in the GET version, we process a response, but do it another way. We get a status of a response with the status method call of HttpResponse, and check whether it's successful, with the is_sucess method call.

For successful responses, we use the json method of HttpResponse to get a Future that collects a body and deserializes it from JSON. If the response wasn't successful, we return an error to the client. Now, we have methods to send requests to other microservices, and can implement handlers for every route.

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

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