GET requests

To send GET requests, we create a get_request function that expects a url parameter and returns a Future instance with binary data:

fn get_request(url: &str) -> impl Future<Item = Vec<u8>, Error = Error> {
client::ClientRequest::get(url)
.finish().into_future()
.and_then(|req| {
req.send()
.map_err(Error::from)
.and_then(|resp| resp.body().from_err())
.map(|bytes| bytes.to_vec())
})
}

We use ClientRequestBuilder to create the ClientRequest instance. The ClientRequest struct already has shortcuts that create builders with a preset HTTP method. We call the get method that only sets the Method::GET value to a request that is implemented as the calling method of the ClientRequestBuilder instance. You can also use a builder to set extra headers or cookies. When you are done with these values, you have to create a ClientRequest instance from a builder by calling one of the following methods:

  • body sets a body value to binary data that can be converted Into<Body>
  • json sets a body value to any type that can be serialized into JSON value
  • form sets a body value to a type that can be serialized with serde_urlencoded: serializer
  • streaming consumes a body value from a Stream instance
  • finish creates a request without a body value

We use finish, because GET requests don't contain a body value. All these methods return a Result with a ClientRequest instance as a successful value. We don't unwrap the Result and will convert it into a Future value with  the into_future method call to return an Error value to a client if the handler can't even build a request.

Since we have a Future value, we can use the and_then method to add the next processing step. We call the send method of a ClientRequest to create a SendRequest instance, which implements the Future trait and sends a request to a server. Since the send call can return the SendRequestError error type, we wrap it with failure::Error.

If a request has sent successfully we can take a MessageBody value with the body method call. This method is a part of the HttpMessage trait. MessageBody also implements a Future trait with a Bytes value and we use the and_then method to extend a chain of futures and transform a value from SendRequest to Bytes.

Finally, we use the to_vec method of Bytes to convert it into Vec<u8> and provide this value as a response to a client. We have finished our method that proxies GET requests to another microservice. Let's create a similar method for POST requests.

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

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