Trait axum::handler::Handler

source ·
pub trait Handler<T, S, B = Body>: Clone + Send + Sized + 'static {
    type Future: Future<Output = Response> + Send + 'static;

    fn call(self, req: Request<B>, state: S) -> Self::Future;

    fn layer<L, NewReqBody>(
        self,
        layer: L
    ) -> Layered<L, Self, T, S, B, NewReqBody>
    where
        L: Layer<HandlerService<Self, T, S, B>> + Clone,
        L::Service: Service<Request<NewReqBody>>
, { ... } fn with_state(self, state: S) -> HandlerService<Self, T, S, B> { ... } }
Expand description

Trait for async functions that can be used to handle requests.

You shouldn’t need to depend on this trait directly. It is automatically implemented to closures of the right types.

See the module docs for more details.

Converting Handlers into Services

To convert Handlers into Services you have to call either HandlerWithoutStateExt::into_service or Handler::with_state:

use tower::Service;
use axum::{
    extract::State,
    body::Body,
    http::Request,
    handler::{HandlerWithoutStateExt, Handler},
};

// this handler doesn't require any state
async fn one() {}
// so it can be converted to a service with `HandlerWithoutStateExt::into_service`
assert_service(one.into_service());

// this handler requires state
async fn two(_: State<String>) {}
// so we have to provide it
let handler_with_state = two.with_state(String::new());
// which gives us a `Service`
assert_service(handler_with_state);

// helper to check that a value implements `Service`
fn assert_service<S>(service: S)
where
    S: Service<Request<Body>>,
{}

Debugging handler type errors

For a function to be used as a handler it must implement the Handler trait. axum provides blanket implementations for functions that:

  • Are async fns.
  • Take no more than 16 arguments that all implement FromRequest.
  • Returns something that implements IntoResponse.
  • If a closure is used it must implement Clone + Send and be 'static.
  • Returns a future that is Send. The most common way to accidentally make a future !Send is to hold a !Send type across an await.

Unfortunately Rust gives poor error messages if you try to use a function that doesn’t quite match what’s required by Handler.

You might get an error like this:

error[E0277]: the trait bound `fn(bool) -> impl Future {handler}: Handler<_, _>` is not satisfied
   --> src/main.rs:13:44
    |
13  |     let app = Router::new().route("/", get(handler));
    |                                            ^^^^^^^ the trait `Handler<_, _>` is not implemented for `fn(bool) -> impl Future {handler}`
    |
   ::: axum/src/handler/mod.rs:116:8
    |
116 |     H: Handler<T, B>,
    |        ------------- required by this bound in `axum::routing::get`

This error doesn’t tell you why your function doesn’t implement Handler. It’s possible to improve the error with the debug_handler proc-macro from the axum-macros crate.

Required Associated Types§

The type of future calling this handler returns.

Required Methods§

Call the handler with the given request.

Provided Methods§

Apply a tower::Layer to the handler.

All requests to the handler will be processed by the layer’s corresponding middleware.

This can be used to add additional processing to a request for a single handler.

Note this differs from routing::Router::layer which adds a middleware to a group of routes.

If you’re applying middleware that produces errors you have to handle the errors so they’re converted into responses. You can learn more about doing that here.

Example

Adding the tower::limit::ConcurrencyLimit middleware to a handler can be done like so:

use axum::{
    routing::get,
    handler::Handler,
    Router,
};
use tower::limit::{ConcurrencyLimitLayer, ConcurrencyLimit};

async fn handler() { /* ... */ }

let layered_handler = handler.layer(ConcurrencyLimitLayer::new(64));
let app = Router::new().route("/", get(layered_handler));

Convert the handler into a Service by providing the state

Implementors§