Typed HTTP with Hyper

The hyper crate can parse HTTP messages, and has an elegant design with focus on strongly typed APIs. It is designed as a type-safe abstraction for raw HTTP requests, as opposed to a common theme in HTTP libraries: describing everything as strings. For example, HTTP status codes in Hyper are defined as enums, for example, the type StatusCode. The same goes for pretty much everything that can be strongly typed, such as HTTP methods, MIME types, HTTP headers, and so on.

Hyper has both client and server functionality split into separate modules. The client side allows you to build and make HTTP requests with a configurable request body, headers, and other low-level configurations. The server side allows you to open a listening socket and attach request handlers to it. However, it does not include any request route handler implementation – that is left to web frameworks. It is designed to be used as a foundational crate to build higher-level web frameworks. It uses the same tokio and futures async abstractions under the hood and thus is very performant.

At its core, Hyper has the concept  Service trait concept:

pub trait Service {
    type ReqBody: Payload;
    type ResBody: Payload;
    type Error: Into<Box<dyn StdError + Send + Sync>>;
    type Future: Future<Item = Response<Self::ResBody>, Error = Self::Error>;
    fn call(&mut self, req: Request<Self::ReqBody>) -> Self::Future;
}

The Service trait represents a type that handles HTTP requests that are sent from any client and returns a Response, which is a future. The core API of this trait that types need to implement is the call method, which takes in a Request that's parameterized over a generic type Body and returns a Future that resolves to a Response, which is parameterized over the associated type ResBody. We don't need to manually implement this trait, as hyper includes a bunch of factory methods that can implement the Service trait for you. You simply need to provide a function that takes HTTP requests and returns responses.

In the following section, we'll explore both the client and server APIs of hyper. Let's start by exploring the server APIs by building a URL shortener from scratch.

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

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