axum/examples/global-404-handler/src/main.rs

45 lines
1.2 KiB
Rust

//! Run with
//!
//! ```not_rust
//! cargo run -p example-global-404-handler
//! ```
use axum::{
http::StatusCode,
response::{Html, IntoResponse},
routing::get,
Router,
};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_global_404_handler=debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.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);
// run it
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).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")
}