Adding a service function

In the previous section, we implemented simple services based on service_fn_ok functions, which expect the service function not to throw any errors. There are also service_fn functions, which can be used to create handlers that can return an error. These are more suitable for asynchronous Future results. As we saw previously, the Future trait has two associated types: one for a successful result and one for an error. The service_fn function expects the result to be converted into future with the IntoFuture trait. You can read more about the futures crate and its types in the next chapter.

Let's change the previous service function into one that returns the Future instance:

let server = builder.serve(|| service_fn(microservice_handler));

Then add this unimplemented service function:

fn microservice_handler(req: Request<Body>)
-> impl Future<Item=Response<Body>, Error=Error>
{
unimplemented!();
}

Similar to the previous one, this function expects a Request, but it doesn't return a simple Response instance. Instead, it returns a future result. Since Future is a trait (which doesn't have a size), we can't return an unsized entity from the function and we have to wrap it in a Box. However, in this case, we used a brand new approach, which is the impl trait. This allows us to return an implementation of the trait by value, rather than by reference. Our future can be resolved to a hyper::Response<Body> item or a hyper::Error error type. You should import the necessary types if you've started a project from scratch and aren't using the code examples included with this book:

use futures::{future, Future};
use hyper::{Body, Error, Method, Request, Response, Server, StatusCode};
use hyper::service::service_fn;

We also imported the Future trait from the futures crate. Make sure you're either using edition = "2018" in the Cargo.toml file, or importing the crates in main.rs:

extern crate futures;
extern crate hyper;

We started by importing the types to the code, but we still have to import the crates in the Cargo.toml file.  Add these crates in the dependency list of your Cargo.toml:

[dependencies]
futures = "0.1"
hyper = "0.12"
Everything is now ready to implement a service handler.
I prefer to order dependencies from generic to more specific. Alternatively, you can use alphabetical order.
..................Content has been hidden....................

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