mirror of
https://github.com/tokio-rs/axum.git
synced 2025-10-02 15:24:54 +00:00

With https://github.com/tokio-rs/axum/pull/404 and https://github.com/tokio-rs/axum/pull/402 all routes now have the same types and thus we don't need to nest them but can instead store them all in a map. This simplifies the routing quite a bit and is faster as well. High level changes: - Routes are now stored in a `HashMap<RouteId, Route<B>>`. - `Router::or` is renamed to `Router::merge` because thats what it does now. It copies all routes from one router to another. This also means overlapping routes will cause a panic which is nice win. - `Router::merge` now only accepts `Router`s so added `Router::fallback` for adding a global 404 handler. - The `Or` service has been removed. - `Router::layer` now only adds layers to the routes you actually have meaning middleware runs _after_ routing. I believe that addresses https://github.com/tokio-rs/axum/issues/380 but will test that on another branch.
46 lines
1.1 KiB
Rust
46 lines
1.1 KiB
Rust
//! Run with
|
|
//!
|
|
//! ```not_rust
|
|
//! cargo run -p example-global-404-handler
|
|
//! ```
|
|
|
|
use axum::{
|
|
handler::Handler,
|
|
http::StatusCode,
|
|
response::{Html, IntoResponse},
|
|
routing::get,
|
|
Router,
|
|
};
|
|
use std::net::SocketAddr;
|
|
|
|
#[tokio::main]
|
|
async fn main() {
|
|
// Set the RUST_LOG, if it hasn't been explicitly defined
|
|
if std::env::var_os("RUST_LOG").is_none() {
|
|
std::env::set_var("RUST_LOG", "example_global_404_handler=debug")
|
|
}
|
|
tracing_subscriber::fmt::init();
|
|
|
|
// build our application with a route
|
|
let app = Router::new().route("/", get(handler));
|
|
|
|
// add a fallback service for handling routes to unknown paths
|
|
let app = app.fallback(handler_404.into_service());
|
|
|
|
// run it
|
|
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
|
tracing::debug!("listening on {}", addr);
|
|
axum::Server::bind(&addr)
|
|
.serve(app.into_make_service())
|
|
.await
|
|
.unwrap();
|
|
}
|
|
|
|
async fn handler() -> Html<&'static str> {
|
|
Html("<h1>Hello, World!</h1>")
|
|
}
|
|
|
|
async fn handler_404() -> impl IntoResponse {
|
|
(StatusCode::NOT_FOUND, "nothing to see here")
|
|
}
|