🧑‍💻 Enhance static file service config

This commit is contained in:
Manuel Cillero 2023-10-29 21:20:55 +01:00
parent 6ac4c9ce33
commit cb87b11845
6 changed files with 69 additions and 27 deletions

View file

@ -30,9 +30,9 @@ max_pool_size = 5
# Los archivos estáticos requeridos por la aplicación se integran de manera
# predeterminada en el binario ejecutable. Sin embargo, durante el desarrollo
# puede resultar útil servir estos archivos desde su propio directorio para
# evitar compilar cada vez que se modifican. En este caso, normalmente, basta
# con indicar la ruta "../ruta/static".
static_files = ""
# evitar recompilar cada vez que se modifican. En este caso bastaría con
# indicar la ruta completa al directorio raiz del proyecto.
pagetop_project_dir = ""
[log]
# Traza de ejecución: "Error", "Warn", "Info", "Debug" o "Trace".

View file

@ -155,7 +155,7 @@ pub static CONFIG: LazyStatic<ConfigData> = LazyStatic::new(|| {
).unwrap()
// Añade la configuración local reservada del entorno. Por defecto 'default.local.toml'.
.merge(
File::with_name(&concat_string!(CONFIG_DIR, "/", run_mode, ".local.toml"))
File::with_name(&concat_string!(CONFIG_DIR, "/local.", run_mode, ".toml"))
.required(false),
).unwrap()
// Añade la configuración local reservada general. Por defecto 'local.toml'.
@ -269,10 +269,10 @@ pub struct Database {
pub struct Dev {
/// Los archivos estáticos requeridos por la aplicación se integran de manera predeterminada en
/// el binario ejecutable. Sin embargo, durante el desarrollo puede resultar útil servir estos
/// archivos desde su propio directorio para evitar compilar cada vez que se modifican. En este
/// caso, normalmente, basta con indicar la ruta "../ruta/static".
/// archivos desde su propio directorio para evitar recompilar cada vez que se modifican. En
/// este caso bastaría con indicar la ruta completa al directorio raíz del proyecto.
/// Por defecto: *""*.
pub static_files: String,
pub pagetop_project_dir: String,
}
#[derive(Debug, Deserialize)]
@ -335,7 +335,7 @@ default_settings!(
"database.max_pool_size" => 5,
// [dev]
"dev.static_files" => "",
"dev.pagetop_project_dir" => "",
// [log]
"log.tracing" => "Info",

View file

@ -1,7 +1,7 @@
use crate::core::action::add_action;
use crate::core::module::ModuleRef;
use crate::core::theme::all::THEMES;
use crate::{new_static_files, service, service_for_static_files, trace, LazyStatic};
use crate::{config, new_static_files, service, service_for_static_files, trace, LazyStatic};
#[cfg(feature = "database")]
use crate::db::*;
@ -157,7 +157,11 @@ pub fn run_migrations() {
// CONFIGURE SERVICES ******************************************************************************
pub fn configure_services(scfg: &mut service::web::ServiceConfig) {
service_for_static_files!(scfg, "/base", base);
service_for_static_files!(
scfg,
base => "/base",
[&config::SETTINGS.dev.pagetop_project_dir, "pagetop/static/base"]
);
for m in ENABLED_MODULES.read().unwrap().iter() {
m.configure_service(scfg);
}

View file

@ -35,23 +35,29 @@ macro_rules! new_static_files {
#[macro_export]
macro_rules! service_for_static_files {
( $scfg:ident, $path:expr, $bundle:ident ) => {{
( $scfg:ident, $bundle:ident => $path:expr $(, [$root:expr, $relative:expr])? ) => {{
$crate::paste! {
let static_files = &$crate::config::SETTINGS.dev.static_files;
if static_files.is_empty() {
$scfg.service($crate::service::ResourceFiles::new(
$path,
[<static_files_ $bundle>]::$bundle(),
));
} else {
$scfg.service(
$crate::service::ActixFiles::new(
let span = $crate::trace::debug_span!("Configuring static files ", path = $path);
let _ = span.in_scope(|| {
let mut serve_embedded:bool = true;
$(
if !$root.is_empty() && !$relative.is_empty() {
if let Ok(absolute) = $crate::util::absolute_dir($root, $relative) {
$scfg.service($crate::service::ActixFiles::new(
$path,
absolute,
).show_files_listing());
serve_embedded = false
}
}
)?
if serve_embedded {
$scfg.service($crate::service::ResourceFiles::new(
$path,
$crate::concat_string!(static_files, $path),
)
.show_files_listing(),
);
}
[<static_files_ $bundle>]::$bundle(),
));
}
});
}
}};
}

View file

@ -18,7 +18,7 @@
use crate::{config, LazyStatic};
pub use tracing::{debug, error, info, trace, warn};
pub use tracing::{event, span, Level};
pub use tracing::{debug_span, error_span, info_span, trace_span, warn_span};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::EnvFilter;

View file

@ -1,6 +1,9 @@
//! Functions and macro helpers.
use crate::Handle;
use crate::{trace, Handle};
use std::io;
use std::path::PathBuf;
// *************************************************************************************************
// FUNCTIONS HELPERS.
@ -56,6 +59,35 @@ pub fn single_type_name<T: ?Sized>() -> &'static str {
partial_type_name(std::any::type_name::<T>(), 1)
}
pub fn absolute_dir(
root_path: impl Into<String>,
relative_path: impl Into<String>,
) -> Result<String, io::Error> {
let root_path = PathBuf::from(root_path.into());
let full_path = root_path.join(relative_path.into());
let absolute_dir = full_path.to_string_lossy().into();
if !full_path.is_absolute() {
let message = format!("Path \"{}\" is not absolute", absolute_dir);
trace::warn!(message);
return Err(io::Error::new(io::ErrorKind::InvalidInput, message));
}
if !full_path.exists() {
let message = format!("Path \"{}\" does not exist", absolute_dir);
trace::warn!(message);
return Err(io::Error::new(io::ErrorKind::NotFound, message));
}
if !full_path.is_dir() {
let message = format!("Path \"{}\" is not a directory", absolute_dir);
trace::warn!(message);
return Err(io::Error::new(io::ErrorKind::InvalidInput, message));
}
Ok(absolute_dir)
}
// *************************************************************************************************
// MACRO HELPERS.
// *************************************************************************************************