Trait aitch::Handler[][src]

pub trait Handler<ReqBody> where
    ReqBody: Body,
    Self: Send + Sync + 'static, 
{ type Resp: Responder; fn handle(&self, _: Request<ReqBody>, _: ResponseBuilder) -> Self::Resp; }

A trait indicating that the type can be used to handler to a HTTP request.

The Handler trait is most commonly used through functions of the following type, for which it is automatically implemented:

This example is not tested
Fn(http::Request<impl Body>, http::response::Builder) -> impl Responder

It can also be implemented manually for more complex types, which store state associated with the handler.

Example

A function which implements the Handler trait:

fn handler(_: http::Request<()>, mut resp: ResponseBuilder) -> impl Responder {
    resp.body("Hello, world".to_owned())
}

A more complex type can also implement the Handler trait directly:

struct ComplexHandler {
    message: String
}

impl Handler<()> for ComplexHandler {
    type Resp = http::Result<http::Response<String>>;

    fn handle(&self, _: Request<()>, mut resp: ResponseBuilder) -> Self::Resp {
        resp.body(self.message.clone())
    }
}

Storing a Handler

If you need to store a Handler, the BoxedHandler type (and corresponding box_handler function) can be used to erase the generic types of the handler.

This can be particularly useful if you need to store multiple handlers (such as in a request router) which may deal with different request/response bodies, or use different Responder types.

Associated Types

The Responder type returned by this Handler.

Required Methods

Handles an incoming HTTP request, returning a Responder describing a HTTP response.

Implementors