2021-08-03 17:00:21 +02:00
|
|
|
//! 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() {
|
2021-08-05 11:25:03 +02:00
|
|
|
// Set the RUST_LOG, if it hasn't been explicitly defined
|
|
|
|
if std::env::var("RUST_LOG").is_err() {
|
|
|
|
std::env::set_var("RUST_LOG", "404=debug")
|
|
|
|
}
|
2021-08-05 19:43:03 +02:00
|
|
|
tracing_subscriber::fmt::init();
|
2021-08-03 17:00:21 +02:00
|
|
|
|
|
|
|
// 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);
|
2021-08-04 15:38:51 +02:00
|
|
|
axum::Server::bind(&addr)
|
2021-08-03 17:00:21 +02:00
|
|
|
.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> {
|
2021-08-06 01:15:23 +02:00
|
|
|
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();
|
2021-08-03 17:00:21 +02:00
|
|
|
}
|
|
|
|
|
2021-08-06 01:15:23 +02:00
|
|
|
response
|
2021-08-03 17:00:21 +02:00
|
|
|
}
|