axum/examples/404.rs
Spencer Gilbert 3cd0c0fd45
Set RUST_LOG environment var for all examples using tracing (#123)
* Set RUST_LOG environment var for all examples using tracing

Signed-off-by: Spencer Gilbert <spencer.gilbert@gmail.com>

* Update examples/multipart_form.rs

Co-authored-by: David Pedersen <david.pdrsn@gmail.com>
2021-08-05 11:25:03 +02:00

52 lines
1.3 KiB
Rust

//! 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() {
// 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")
}
tracing_subscriber::fmt::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.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);
axum::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()
}