From 1bda638c6b28f07c323dd66e91c36e4c6b61fcfd Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Thu, 19 Aug 2021 22:50:42 +0200 Subject: [PATCH] Simplify 404 example using `or` --- examples/global-404-handler/src/main.rs | 26 +++++++------------------ 1 file changed, 7 insertions(+), 19 deletions(-) diff --git a/examples/global-404-handler/src/main.rs b/examples/global-404-handler/src/main.rs index 16783b2f..c5c316f4 100644 --- a/examples/global-404-handler/src/main.rs +++ b/examples/global-404-handler/src/main.rs @@ -5,14 +5,11 @@ //! ``` use axum::{ - body::{box_body, Body, BoxBody}, - handler::get, - http::{Response, StatusCode}, + handler::{get, Handler}, response::Html, Router, }; use std::net::SocketAddr; -use tower::util::MapResponseLayer; #[tokio::main] async fn main() { @@ -23,10 +20,10 @@ async fn main() { tracing_subscriber::fmt::init(); // build our application with a route - let app = Router::new() - .route("/", get(handler)) - // make sure this is added as the very last thing - .layer(MapResponseLayer::new(map_404)); + let app = Router::new().route("/", get(handler)); + + // make sure this is added as the very last thing + let app = app.or(handler_404.into_service()); // run it let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); @@ -41,15 +38,6 @@ async fn handler() -> Html<&'static str> { Html("

Hello, World!

") } -fn map_404(response: Response) -> Response { - if response.status() == StatusCode::NOT_FOUND - || response.status() == StatusCode::METHOD_NOT_ALLOWED - { - return Response::builder() - .status(StatusCode::NOT_FOUND) - .body(box_body(Body::from("nothing to see here"))) - .unwrap(); - } - - response +async fn handler_404() -> &'static str { + "nothing to see here" }