mirror of
https://github.com/tokio-rs/axum.git
synced 2025-01-11 12:31:25 +01:00
Simplify 404 example using or
This commit is contained in:
parent
23dcf3631e
commit
1bda638c6b
1 changed files with 7 additions and 19 deletions
|
@ -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("<h1>Hello, World!</h1>")
|
||||
}
|
||||
|
||||
fn map_404(response: Response<BoxBody>) -> Response<BoxBody> {
|
||||
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"
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue