mirror of
https://github.com/tokio-rs/axum.git
synced 2026-09-08 00:00:24 +02:00
Simplify 404 example using or
This commit is contained in:
@@ -5,14 +5,11 @@
|
|||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use axum::{
|
use axum::{
|
||||||
body::{box_body, Body, BoxBody},
|
handler::{get, Handler},
|
||||||
handler::get,
|
|
||||||
http::{Response, StatusCode},
|
|
||||||
response::Html,
|
response::Html,
|
||||||
Router,
|
Router,
|
||||||
};
|
};
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use tower::util::MapResponseLayer;
|
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
@@ -23,10 +20,10 @@ async fn main() {
|
|||||||
tracing_subscriber::fmt::init();
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
// build our application with a route
|
// build our application with a route
|
||||||
let app = Router::new()
|
let app = Router::new().route("/", get(handler));
|
||||||
.route("/", get(handler))
|
|
||||||
// make sure this is added as the very last thing
|
// make sure this is added as the very last thing
|
||||||
.layer(MapResponseLayer::new(map_404));
|
let app = app.or(handler_404.into_service());
|
||||||
|
|
||||||
// run it
|
// run it
|
||||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||||
@@ -41,15 +38,6 @@ async fn handler() -> Html<&'static str> {
|
|||||||
Html("<h1>Hello, World!</h1>")
|
Html("<h1>Hello, World!</h1>")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn map_404(response: Response<BoxBody>) -> Response<BoxBody> {
|
async fn handler_404() -> &'static str {
|
||||||
if response.status() == StatusCode::NOT_FOUND
|
"nothing to see here"
|
||||||
|| response.status() == StatusCode::METHOD_NOT_ALLOWED
|
|
||||||
{
|
|
||||||
return Response::builder()
|
|
||||||
.status(StatusCode::NOT_FOUND)
|
|
||||||
.body(box_body(Body::from("nothing to see here")))
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
response
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user