Fixup the Axum Router so that / correctly redirects to /index.html. Make it easy to keep adding template pages.

This commit is contained in:
Herbert Wolverson 2024-07-03 08:55:03 -05:00
parent 8eaa9c6324
commit 26d5250472
2 changed files with 46 additions and 18 deletions

View File

@ -1,7 +1,12 @@
use std::path::Path;
use axum::Router;
use log::info;
use tokio::net::TcpListener;
use anyhow::Result;
use anyhow::{bail, Result};
use axum::response::Redirect;
use axum::routing::get;
use tower_http::services::ServeDir;
use lqos_config::load_config;
use crate::node_manager::{static_pages::{static_routes, vendor_route}, ws::websocket_router};
use crate::node_manager::local_api::local_api;
@ -12,14 +17,32 @@ pub async fn spawn_webserver() -> Result<()> {
// TODO: port change is temporary
let listener = TcpListener::bind(":::9223").await?;
// Check that static content is available and setup the path
let config = load_config()?;
let static_path = Path::new(&config.lqos_directory)
.join("bin")
.join("static2");
if !static_path.exists() {
bail!("Static path not found for webserver (vin/static2/");
}
// Construct the router from parts
let router = Router::new()
.route("/", get(redirect_to_index))
.nest("/websocket/", websocket_router())
.nest("/vendor", vendor_route()?) // Serve /vendor as purely static
.nest("/", static_routes()?)
.nest("/local-api", local_api());
.nest("/local-api", local_api())
.fallback_service(ServeDir::new(static_path));
info!("Webserver listening on :: port 9223");
axum::serve(listener, router).await?;
Ok(())
}
/// Provides a redirect service that sends visitors
/// to the index.html page.
async fn redirect_to_index() -> Redirect {
Redirect::permanent("/index.html")
}

View File

@ -24,24 +24,29 @@ pub(super) fn vendor_route() -> Result<Router> {
pub(super) fn static_routes() -> Result<Router> {
let config = load_config()?;
let static_path = Path::new(&config.lqos_directory)
.join("bin")
.join("static2");
let index = Path::new(&config.lqos_directory)
.join("bin")
.join("static2")
.join("index.html");
if !static_path.exists() {
bail!("Static path not found for webserver (vin/static2/");
// Add HTML pages to serve directly to this list, otherwise
// they won't have template + authentication applied to them.
let html_pages = [
"index.html"
];
// Iterate through pages and construct the router
let mut router = Router::new();
for page in html_pages.iter() {
let path = Path::new(&config.lqos_directory)
.join("bin")
.join("static2")
.join(page);
if !path.exists() {
bail!("Missing webpage: {page}");
}
router = router.route_service(&format!("/{page}"), ServeFile::new(path));
}
let router = Router::new()
.nest_service("/index.html", ServeFile::new(index.clone()))
.nest_service("/", ServeDir::new(static_path))
router = router
.route_layer(axum::middleware::from_fn(apply_templates));
Ok(router)
}