Axum Pass Value to Router Function

async fn foo(Path(name):Path<String>) -> impl IntoResponse
                 //i need x here but don't know how to get
async fn main()
                  let x:u8 = 3;
                  let app = Router::new().route("/:name", get(foo)); //how to pass x into foo
                  let listener = tokio::net::TcpListener::bind("").await.unwrap();
                  axum::serve(listener, app).await.unwrap();

Hi, I'm pretty new on axum. I'm trying to reach x from foo function (also i will use name which comes from /:name). I don't know how to do.

get accepts a closure:

use axum::{extract::Path, response::IntoResponse, routing::get, Router};

async fn foo(x: u8, Path(name): Path<String>) -> impl IntoResponse {
    dbg!(x, name);

async fn main() {
    let x: u8 = 3;
    let app = Router::new().route("/:name", get(move |name| foo(x, name)));
    let listener = tokio::net::TcpListener::bind("")
    axum::serve(listener, app).await.unwrap();
1 Like

On top of @tbflemming's answer, you should familiarize youself with how you are supposed to share state in request handlers in Axum: axum - Rust.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.