use axum::body::Body;
use axum::extract::Request;
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use include_dir::{Dir, include_dir};
pub static DEFAULT_SITE_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/website-default");
fn lookup(rel_path: &str) -> Option<&'static [u8]> {
let trimmed = rel_path.trim_start_matches('/');
DEFAULT_SITE_DIR.get_file(trimmed).map(|f| f.contents())
}
pub async fn serve(req: Request<Body>) -> Response {
let raw_path = req.uri().path();
let req_path = if raw_path == "/" || raw_path.ends_with('/') {
"/index.html".to_string()
} else {
raw_path.to_string()
};
let (bytes, mime) = match lookup(&req_path) {
Some(b) => (
b,
mime_guess::from_path(&req_path)
.first_or_octet_stream()
.to_string(),
),
None => match lookup("/index.html") {
Some(b) => (b, "text/html; charset=utf-8".to_string()),
None => {
return (StatusCode::NOT_FOUND, "default site not embedded").into_response();
}
},
};
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, mime)
.header(header::CACHE_CONTROL, "public, max-age=60")
.body(Body::from(bytes))
.unwrap_or_else(|_| (StatusCode::INTERNAL_SERVER_ERROR, "response build").into_response())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn embedded_dir_has_index() {
assert!(
DEFAULT_SITE_DIR.get_file("index.html").is_some(),
"index.html missing from website-default/ — was the source dir deleted?"
);
}
#[test]
fn lookup_returns_index_bytes() {
let bytes = lookup("/index.html").expect("index.html");
let body = std::str::from_utf8(bytes).unwrap();
assert!(
body.contains("Verifiable Trust Community"),
"default index.html drifted: {body}"
);
}
#[test]
fn lookup_misses_on_unknown_path() {
assert!(lookup("/no-such-file").is_none());
}
}