Trait gotham::handler::Handler[][src]

pub trait Handler: Send {
    fn handle(self, state: State) -> Pin<Box<HandlerFuture>>;
}
Expand description

A Handler is an asynchronous function, taking a State value which represents the request and related runtime state, and returns a future which resolves to a response.

This represents the common entry point for the parts of a Gotham application, and is used with the Router API to describe how a request should be dispatched and handled.

The Handler is created and consumed by each request. In the most common case (a bare function acting as a Handler) the Handler + Copy traits allow the Handler to be copied for each request, and the copy consumed. For a closure or a custom handler, the NewHandler implementation creates a Handler value for each request.

Examples

The simplest kind of handler is a bare function which returns a synchronous response. This is useful when we don’t need to do any I/O before generating a response.

fn my_handler(_state: State) -> (State, Response<Body>) {
    // Implementation elided.
}

An asynchronous handler returns a HandlerFuture that will resolve to the response. For example, this allows I/O work to begin, and for the Gotham app to continue generating a response once the work completes.

fn async_handler(_state: State) -> Pin<Box<HandlerFuture>> {
    // Implementation elided.
}

A closure can implement Handler automatically, in the same way as a bare function. When constructing a Handler in this way, a wrapping closure must also be used to implement the NewHandler trait.

let new_handler = || {
    let handler = |state: State| {
        // Implementation elided.
    };
    Ok(handler)
};

// Pass `new_handler` to the router, using the `to_new_handler` API.

A custom handler, which implements the NewHandler and Handler traits directly for greater control. See the NewHandler trait for more examples of custom handlers.

#[derive(Copy, Clone)]
struct MyCustomHandler;

impl NewHandler for MyCustomHandler {
    type Instance = Self;

    fn new_handler(&self) -> anyhow::Result<Self::Instance> {
        Ok(*self)
    }
}

impl Handler for MyCustomHandler {
    fn handle(self, _state: State) -> Pin<Box<HandlerFuture>> {
        // Implementation elided.
    }
}

Required methods

Handles the request, returning a boxed future which resolves to a response.

Implementors