mylloon.fr/src/main.rs

106 lines
2.8 KiB
Rust
Raw Normal View History

use std::{
fs::{self, File},
io::{self, Write},
path::Path,
};
use actix_files::Files;
2023-02-08 22:14:57 +01:00
use actix_web::{web, App, HttpServer};
use glob::glob;
use minify_html::{minify, Cfg};
2023-02-09 11:19:53 +01:00
2023-02-08 20:49:05 +01:00
mod config;
2023-02-09 11:19:53 +01:00
mod template;
2023-02-08 20:49:05 +01:00
2023-02-09 10:59:06 +01:00
#[path = "routes/agreements.rs"]
mod agreements;
2023-02-08 20:49:05 +01:00
2023-02-08 22:27:40 +01:00
#[path = "routes/not_found.rs"]
mod not_found;
2023-02-09 10:59:06 +01:00
#[path = "routes/index.rs"]
mod index;
#[path = "routes/networks.rs"]
mod networks;
#[path = "routes/portfolio.rs"]
mod portfolio;
2023-02-08 22:14:57 +01:00
2023-02-08 20:49:05 +01:00
#[actix_web::main]
async fn main() -> io::Result<()> {
let config = config::get_config("/config/config.toml");
2023-02-08 20:49:05 +01:00
2023-02-09 11:36:22 +01:00
let addr = ("127.0.0.1", config.port.unwrap_or(8080));
println!(
"Listening to {}://{}:{}",
config.clone().scheme.unwrap_or("http".to_string()),
addr.0,
addr.1
);
2023-02-08 20:58:24 +01:00
let static_folder = "static";
2023-02-09 10:24:29 +01:00
let dist_folder = format!("dist/{static_folder}");
// The static folder is minimized only in release mode
2023-02-09 00:10:21 +01:00
let folder = if cfg!(debug_assertions) {
format!("{static_folder}/")
} else {
2023-02-09 10:24:29 +01:00
let cfg = Cfg::spec_compliant();
for entry in glob(&format!("{static_folder}/**/*.*")).unwrap() {
let path = entry.unwrap();
2023-02-09 10:24:29 +01:00
let path_with_dist = path.to_string_lossy().replace(static_folder, &dist_folder);
2023-02-09 10:24:29 +01:00
// Create folders
let new_path = Path::new(&path_with_dist);
fs::create_dir_all(new_path.parent().unwrap()).unwrap();
2023-02-09 10:24:29 +01:00
let mut copy = true;
if let Some(ext) = path.extension() {
// List of files who should be minified
if ["html", "css", "js", "svg", "webmanifest", "xml"]
.iter()
.any(|item| ext.to_string_lossy().to_lowercase().contains(item))
{
// We won't copy, we'll minify
copy = false;
// Minify
let data = fs::read(&path).unwrap();
let minified = minify(&data, &cfg);
// Write files
let mut file = File::create(&path_with_dist)?;
file.write_all(&minified)?;
}
}
if copy {
// If no minification is needed
fs::copy(path, path_with_dist)?;
}
}
format!("{dist_folder}/")
};
2023-02-08 22:14:57 +01:00
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(config.clone()))
.service(index::page)
.service(agreements::security)
2023-02-08 22:22:20 +01:00
.service(agreements::humans)
.service(agreements::robots)
.service(agreements::sitemap)
2023-02-09 10:59:06 +01:00
.service(networks::page)
.service(portfolio::page)
.service(Files::new("/", &folder))
2023-02-08 22:27:40 +01:00
.default_service(web::to(not_found::page))
2023-02-08 22:14:57 +01:00
})
.bind(addr)?
.run()
.await
2023-02-02 11:06:27 +01:00
}