Files
VirtWeb/virtweb_backend/src/controllers/static_controller.rs
2025-05-21 20:28:46 +02:00

68 lines
2.1 KiB
Rust

#[cfg(debug_assertions)]
pub use serve_static_debug::{root_index, serve_static_content};
#[cfg(not(debug_assertions))]
pub use serve_static_release::{root_index, serve_static_content};
/// Static API assets hosting
pub mod serve_assets {
use actix_web::{HttpResponse, web};
use rust_embed::RustEmbed;
#[derive(RustEmbed)]
#[folder = "assets/"]
struct Asset;
/// Serve API assets
pub async fn serve_api_assets(file: web::Path<String>) -> HttpResponse {
match Asset::get(&file) {
None => HttpResponse::NotFound().body("File not found"),
Some(asset) => HttpResponse::Ok()
.content_type(asset.metadata.mimetype())
.body(asset.data),
}
}
}
/// Web asset hosting placeholder in debug mode
#[cfg(debug_assertions)]
mod serve_static_debug {
use actix_web::{HttpResponse, Responder};
pub async fn root_index() -> impl Responder {
HttpResponse::Ok().body("Hello world! Debug=on for VirtWeb!")
}
pub async fn serve_static_content() -> impl Responder {
HttpResponse::NotFound().body("Hello world! Static assets are not served in debug mode")
}
}
/// Web asset hosting in release mode
#[cfg(not(debug_assertions))]
mod serve_static_release {
use actix_web::{HttpResponse, Responder, web};
use rust_embed::RustEmbed;
#[derive(RustEmbed)]
#[folder = "static/"]
struct WebAsset;
fn handle_embedded_file(path: &str, can_fallback: bool) -> HttpResponse {
match (WebAsset::get(path), can_fallback) {
(Some(content), _) => HttpResponse::Ok()
.content_type(content.metadata.mimetype())
.body(content.data.into_owned()),
(None, false) => HttpResponse::NotFound().body("404 Not Found"),
(None, true) => handle_embedded_file("index.html", false),
}
}
pub async fn root_index() -> impl Responder {
handle_embedded_file("index.html", false)
}
pub async fn serve_static_content(path: web::Path<String>) -> impl Responder {
handle_embedded_file(path.as_ref(), !path.as_ref().starts_with("static/"))
}
}