minify: minify html on the fly in release mode
This commit is contained in:
parent
895d3ad117
commit
3dfcd542bf
4 changed files with 136 additions and 0 deletions
|
|
@ -16,6 +16,7 @@ rocket_cors = "0.6.0-alpha2"
|
|||
email_address = { workspace = true }
|
||||
chrono-tz = "0.8.2"
|
||||
chrono-humanize = "0.2.2"
|
||||
minify-html = "0.10.8"
|
||||
|
||||
# local crates
|
||||
database_pool = { path = "../database_pool" }
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ mod guards;
|
|||
mod icons;
|
||||
mod id;
|
||||
mod menu;
|
||||
mod minify;
|
||||
mod oauth;
|
||||
mod page;
|
||||
mod response_timer;
|
||||
|
|
@ -18,6 +19,7 @@ mod shutdown;
|
|||
mod tokens;
|
||||
|
||||
pub use crate::email::init as email_init;
|
||||
use crate::minify::Minify;
|
||||
|
||||
pub fn rocket_setup(rocket_builder: Rocket<Build>) -> Rocket<Build> {
|
||||
use cache::CacheControl;
|
||||
|
|
@ -46,6 +48,9 @@ pub fn rocket_setup(rocket_builder: Rocket<Build>) -> Rocket<Build> {
|
|||
// Static assets
|
||||
let rocket_builder = rocket_builder.mount("/", FileServer::from("static"));
|
||||
|
||||
// Minify content
|
||||
let rocket_builder = Minify::rocket(rocket_builder);
|
||||
|
||||
// Routes
|
||||
let rocket_builder = routes::routes(rocket_builder);
|
||||
|
||||
|
|
|
|||
49
crates/ezidam/src/minify.rs
Normal file
49
crates/ezidam/src/minify.rs
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
use rocket::fairing::{self, Fairing, Kind};
|
||||
use rocket::http::ContentType;
|
||||
use rocket::{Build, Request, Response, Rocket};
|
||||
|
||||
pub struct Minify {}
|
||||
|
||||
impl Minify {
|
||||
pub fn rocket(rocket_builder: Rocket<Build>) -> Rocket<Build> {
|
||||
if cfg!(debug_assertions) {
|
||||
rocket_builder
|
||||
} else {
|
||||
rocket_builder.attach(Self {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl Fairing for Minify {
|
||||
fn info(&self) -> fairing::Info {
|
||||
fairing::Info {
|
||||
name: "Minify HTML",
|
||||
kind: Kind::Response,
|
||||
}
|
||||
}
|
||||
|
||||
async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) {
|
||||
if response.content_type() == Some(ContentType::HTML) {
|
||||
let body = response.body_mut();
|
||||
|
||||
if let Ok(original) = body.to_bytes().await {
|
||||
let cfg = minify_html::Cfg {
|
||||
// Be HTML spec compliant
|
||||
do_not_minify_doctype: true,
|
||||
ensure_spec_compliant_unquoted_attribute_values: true,
|
||||
keep_spaces_between_attributes: true,
|
||||
|
||||
// The rest
|
||||
keep_closing_tags: true,
|
||||
keep_html_and_head_opening_tags: true,
|
||||
minify_css: true,
|
||||
minify_js: true,
|
||||
..Default::default()
|
||||
};
|
||||
let minified = minify_html::minify(&original, &cfg);
|
||||
response.set_sized_body(minified.len(), std::io::Cursor::new(minified));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue