Serve static files if no other endpoints match
This commit is contained in:
parent
c4f1cd2201
commit
6cf1b662ae
4 changed files with 195 additions and 1 deletions
|
|
@ -1,7 +1,11 @@
|
|||
mod r#static;
|
||||
|
||||
use axum::{routing::get, Router};
|
||||
|
||||
async fn run() -> anyhow::Result<()> {
|
||||
let app = Router::new().route("/", get(|| async { "Hello, world!" }));
|
||||
let app = Router::new()
|
||||
.route("/", get(|| async { "Hello, world!" }))
|
||||
.fallback(get(r#static::static_handler));
|
||||
|
||||
axum::Server::bind(&"0.0.0.0:8000".parse().unwrap())
|
||||
.serve(app.into_make_service())
|
||||
|
|
|
|||
34
src/static.rs
Normal file
34
src/static.rs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
//! Static files embedded in the binary.
|
||||
|
||||
use axum::{
|
||||
http::{header, StatusCode, Uri},
|
||||
response::IntoResponse,
|
||||
};
|
||||
use rust_embed::RustEmbed;
|
||||
|
||||
#[derive(RustEmbed)]
|
||||
#[folder = "target/static"]
|
||||
pub struct StaticFiles;
|
||||
|
||||
pub struct StaticFile<T>(T);
|
||||
|
||||
impl<T> IntoResponse for StaticFile<T>
|
||||
where
|
||||
T: AsRef<str>,
|
||||
{
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
let path = self.0.as_ref();
|
||||
match StaticFiles::get(path) {
|
||||
Some(file) => {
|
||||
let mime = mime_guess::from_path(path).first_or_octet_stream();
|
||||
([(header::CONTENT_TYPE, mime.as_ref())], file.data).into_response()
|
||||
}
|
||||
None => StatusCode::NOT_FOUND.into_response(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn static_handler(uri: Uri) -> impl IntoResponse {
|
||||
let path = uri.path().trim_start_matches('/').to_string();
|
||||
StaticFile(path)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue