How can i overload handler in axum

75 views Asked by At

Here is the code.

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

#[tokio::main]
async fn main() {
    run().await;
}

async fn run() {
    let app = Router::new()
        .route("/", get(root))
        .route("/:id", get(mirror))
        .route("/:name", get(mirror2));
    let listen = tokio::net::TcpListener::bind("0.0.0.0:8000").await.unwrap();
    axum::serve(listen, app).await.unwrap();
}

async fn root() -> String {
    format!("This is rocket!")
}

async fn mirror(Path(id): Path<isize>) -> String {
    id.to_string()
}
async fn mirror2(Path(name): Path<String>) -> String {
    name
}

Invalid route "/:name": insertion failed due to conflict with previously registered route: /:id

1

There are 1 answers

0
kmdreko On

You cannot. From the documentation on .route():

It is not possible to create segments that only match some types like numbers or regular expression. You must handle that manually in your handlers.

So you'll have to define a single handler taking in a Path<String> and attempt parsing to isize yourself to decide what code to run.