use axum::{
routing::{get, post},
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(root))
.route("/admin", post(admin));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn root() -> &'static str {
"Hello, Root!"
}
async fn admin() -> &'static str {
"Hello, Admin!"
}
This is an example given by axum official, and now I want to wrap this example for convenience
async fn http_srv_new<H, T, S>(addr: &str, routes: Vec<(&str, &str, H)>) -> Result<(), axum::Error>
where
H: Handler<T, S>,
T: 'static,
S: Clone + Send + Sync + 'static,
{
let listener = TcpListener::bind(addr).await.unwrap();
let router = Router::new();
for (path, method_type, method) in routes {
let rou = if method_type == "post" {
post(method)
} else {
get(method)
};
router.route(path, rou);
}
axum::serve(listener, router).await.unwrap();
Ok(())
}
Example call:
#[tokio::main]
async fn main() {
http_srv_new(
"0.0.0.0:3000",
vec![("/", "get", root), ("/admin", "post", admin_handler)],
).await;
}
Now the problem is that the router in the http_srv_new() function is incorrect
the trait bound `for<'a> axum::Router<S>: Service<IncomingStream<'a>>` is not satisfied
the trait `for<'a> Service<IncomingStream<'a>>` is not implemented for `axum::Router<S>`
Help, how can we solve this problem