Files
axum/examples/static-file-server/src/main.rs
T

51 lines
1.6 KiB
Rust
Raw Normal View History

2021-08-02 23:09:09 +02:00
//! Run with
//!
//! ```not_rust
2022-04-29 18:53:41 +02:00
//! cd examples && cargo run -p example-static-file-server
2021-08-02 23:09:09 +02:00
//! ```
2022-05-08 21:52:34 +02:00
use axum::{
http::StatusCode,
response::IntoResponse,
routing::{get, get_service},
Router,
};
use std::{io, net::SocketAddr};
2021-06-06 21:53:22 +02:00
use tower_http::{services::ServeDir, trace::TraceLayer};
2022-03-06 12:37:00 +01:00
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
2021-06-06 21:53:22 +02:00
#[tokio::main]
async fn main() {
2022-03-06 12:37:00 +01:00
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG")
.unwrap_or_else(|_| "example_static_file_server=debug,tower_http=debug".into()),
))
.with(tracing_subscriber::fmt::layer())
.init();
2021-06-06 21:53:22 +02:00
2022-05-08 21:52:34 +02:00
// `SpaRouter` is the easiest way to serve assets at a nested route like `/assets`
// let app = Router::new()
// .route("/foo", get(|| async { "Hi from /foo" }))
// .merge(axum_extra::routing::SpaRouter::new("/assets", "."))
// .layer(TraceLayer::new_for_http());
// for serving assets directly at the root you can use `tower_http::services::ServeDir`
// as the fallback to a `Router`
let app: _ = Router::new()
.route("/foo", get(|| async { "Hi from /foo" }))
.fallback(get_service(ServeDir::new(".")).handle_error(handle_error))
.layer(TraceLayer::new_for_http());
2021-06-06 21:53:22 +02:00
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
2021-06-19 12:50:33 +02:00
.serve(app.into_make_service())
.await
.unwrap();
2021-06-06 21:53:22 +02:00
}
2022-05-08 21:52:34 +02:00
async fn handle_error(_err: io::Error) -> impl IntoResponse {
(StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong...")
}