Search code examples
rustrust-axum

How to conditionally add routes to Axum Router?


I'm using axum and this code to create a server but I get an error:

use axum::{response::Html, routing::get, Router};

async fn handler() -> Html<&'static str> {
    Html("<h1>Hello, World!</h1>")
}

#[tokio::main]
async fn main() {
    let router = Router::new();

    router.route("/", get(handler));

    if true { // I need to check something here
        router.route("/other", get(handler));
    }

    axum::Server::bind(&([127, 0, 0, 1], 3000).into())
        .serve(router.into_make_service())
        .await
        .unwrap();
}
error[E0382]: use of moved value: `router`
  --> src\main.rs:18:16
   |
9  |     let router = Router::new();
   |         ------ move occurs because `router` has type `Router`, which does not implement the `Copy` trait
10 |
11 |     router.route("/", get(handler));
   |     ------ value moved here
...
14 |         router.route("/other", get(handler));
   |         ------ value moved here
...
18 |         .serve(router.into_make_service())
   |                ^^^^^^ value used here after move

I tried with &router but I still get the error. How can I fix this? Should I use .clone()?


Solution

  • Using this code it works:

    let mut router = Router::new();
    router = router.route("/", get(handler));
    
    if true {
        router = router.route(...);
    }