mirror of
https://github.com/tokio-rs/axum.git
synced 2025-03-13 19:27:53 +01:00
Add 404 page example (#97)
This commit is contained in:
parent
be68227d73
commit
b0457c08e8
2 changed files with 47 additions and 0 deletions
46
examples/404.rs
Normal file
46
examples/404.rs
Normal file
|
@ -0,0 +1,46 @@
|
|||
//! Run with
|
||||
//!
|
||||
//! ```not_rust
|
||||
//! cargo run --example 404
|
||||
//! ```
|
||||
|
||||
use axum::{
|
||||
body::{box_body, Body, BoxBody},
|
||||
prelude::*,
|
||||
};
|
||||
use http::{Response, StatusCode};
|
||||
use std::net::SocketAddr;
|
||||
use tower::util::MapResponseLayer;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// build our application with a route
|
||||
let app = route("/", get(handler))
|
||||
// make sure this is added as the very last thing
|
||||
.layer(MapResponseLayer::new(map_404));
|
||||
|
||||
// run it
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
tracing::debug!("listening on {}", addr);
|
||||
hyper::Server::bind(&addr)
|
||||
.serve(app.into_make_service())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn handler() -> response::Html<&'static str> {
|
||||
response::Html("<h1>Hello, World!</h1>")
|
||||
}
|
||||
|
||||
fn map_404(response: Response<BoxBody>) -> Response<BoxBody> {
|
||||
if response.status() != StatusCode::NOT_FOUND {
|
||||
return response;
|
||||
}
|
||||
|
||||
Response::builder()
|
||||
.status(StatusCode::NOT_FOUND)
|
||||
.body(box_body(Body::from("nothing to see here")))
|
||||
.unwrap()
|
||||
}
|
|
@ -16,3 +16,4 @@
|
|||
- [`sessions`](../examples/sessions.rs) - Sessions and cookies using [`async-session`](https://crates.io/crates/async-session).
|
||||
- [`tls_rustls`](../examples/tls_rustls.rs) - TLS with [`tokio-rustls`](https://crates.io/crates/tokio-rustls).
|
||||
- [`chat`](../examples/chat.rs) - Chat application example.
|
||||
- [`404`](../examples/404.rs) - Custom 404 page.
|
||||
|
|
Loading…
Add table
Reference in a new issue