serve frontend by backend if feature flag is set

This commit is contained in:
2022-12-08 13:06:19 +01:00
parent b77b34442b
commit 21520a7b1c
5 changed files with 177 additions and 13 deletions

51
lib/src/embed/mod.rs Normal file
View File

@ -0,0 +1,51 @@
use std::io::Cursor;
use rust_embed::RustEmbed;
use rocket::{Data, Request, Response, Route};
use rocket::http::{ContentType, Method};
use rocket::http::uri::{Segments};
use rocket::http::uri::fmt::Path;
use rocket::route::{Handler, Outcome};
#[cfg(feature = "static")]
#[derive(RustEmbed)]
#[folder = "webroot/"]
struct Asset;
#[cfg(feature = "static")]
#[derive(Clone)]
pub struct CustomHandler {
}
#[cfg(feature = "static")]
impl Into<Vec<Route>> for CustomHandler {
fn into(self) -> Vec<Route> {
vec![
Route::ranked(-2, Method::Get, "/<path..>", self),
]
}
}
#[cfg(feature = "static")]
#[rocket::async_trait]
impl Handler for CustomHandler {
async fn handle<'r>(&self, request: &'r Request<'_>, _: Data<'r>) -> Outcome<'r> {
let path = request.segments::<Segments<'_, Path>>(0..).ok()
.and_then(|segments| segments.to_path_buf(true).ok()).unwrap();
let path = if path.is_dir() || path.to_str() == Some("") {
path.join("index.html")
} else {
path
};
let file_content =
<Asset as RustEmbed>::get(path.to_string_lossy().as_ref()).unwrap();
let content_type: ContentType = path
.extension()
.map(|x| x.to_string_lossy())
.and_then(|x| ContentType::from_extension(&x))
.unwrap_or(ContentType::Plain);
let rsp = Response::build().header(content_type).sized_body(file_content.data.len(), Cursor::new(file_content.data)).finalize();
Outcome::Success(rsp)
}
}

View File

@ -1,9 +1,13 @@
mod parser;
#[macro_use]
extern crate rocket;
mod parser;
#[cfg(feature = "static")]
mod embed;
use rocket::serde::json::Json;
#[cfg(feature = "static")]
use crate::embed::CustomHandler;
use crate::parser::lsblk_parser::{Disk, parse_lsblk};
use crate::parser::mdstat_parser::{MdRaidSystem, parse_mdstat};
@ -20,10 +24,10 @@ fn get_disks() -> Json<Vec<Disk>> {
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
println!("init");
let _rocket = rocket::build()
.mount("/api", routes![get_raid_devices, get_disks])
.launch()
.await?;
let b = rocket::build();
let b = b.mount("/api", routes![get_raid_devices, get_disks]);
#[cfg(feature = "static")]
let b = b.mount("/", CustomHandler{});
let _rocket = b.launch().await?;
Ok(())
}