Skip to content

How to create (and type) higher-order handlers? #517

Answered by davidpdrsn
johnteske asked this question in Q&A
Discussion options

You must be logged in to vote

Yep! You can do this:

use axum::{Router, body::Body, handler::Handler, http::HeaderMap, routing::get};
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(create_handler("foo".to_string())))
        .route("/foo", get(create_handler_with_extractor("foo".to_string())))
        .route("/bar", get(create_handler_with_extractors("foo".to_string())));

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

fn create_handler(s: String) -> impl Handler<Body, ()> {
    || async move {
        s
    }
}

fn create_handler_with_extr…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@johnteske
Comment options

Answer selected by johnteske
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants