Best way to implement an hostname based router? #934
-
Hello, I would like to have different routes depending on the Hostname of the request. Something similar to the following pseudo-code: router.Use(middleware.CleanPath)
router.Use(middleware.SetHTTPContext)
router.Use(middleware.Auth(kernelService, sitesService, membersService))
router.Use(middleware.Timeout(60 * time.Second))
router.Use(middleware.Recoverer)
router.Map("mydomain.com", websiteRoutes)
router.Map("api.mydomain.com", apiRoutes)
router.Map("*", otherRoutes) Where What is the best way to achieve that with axum? Thank you EditFor those interested, I've published the complete code on my blog: https://kerkour.com/rust-axum-hostname-router |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
axum doesn't support routing directly based on the hostname. Instead you have to use the |
Beta Was this translation helpful? Give feedback.
-
In axum6, we can use let router = Router::new()
.route("/", get(main))
.with_state(())
.layer(middleware::from_fn(my_middleware));
async fn my_middleware<B>(Host(host): Host, request: Request<B>, next: Next<B>) -> Response {
let lowcase_host = host.to_lowercase();
if lowcase_host == "example.com" || lowcase_host == "www.example.com" {
return next.run(request).await;
}
StatusCode::NOT_FOUND.into_response()
} Hope that helps others. |
Beta Was this translation helpful? Give feedback.
axum doesn't support routing directly based on the hostname. Instead you have to use the
Host
extractor, check the value in a handler, and forward the request to some other router.