diff options
author | Alex Auvolat <alex@adnab.me> | 2021-12-09 16:03:19 +0100 |
---|---|---|
committer | Alex Auvolat <alex@adnab.me> | 2021-12-09 16:03:19 +0100 |
commit | 64cfb30a85eff8e4077a7253d135b781a3511166 (patch) | |
tree | 5de6bfdb9dbfab4f57acdee3ac51f63b58ff8f3f | |
parent | 9b30f2b7d17cbee39c271d159524202e0ffa297c (diff) | |
download | tricot-64cfb30a85eff8e4077a7253d135b781a3511166.tar.gz tricot-64cfb30a85eff8e4077a7253d135b781a3511166.zip |
Better compression choices
-rw-r--r-- | src/https.rs | 32 | ||||
-rw-r--r-- | src/main.rs | 2 |
2 files changed, 28 insertions, 6 deletions
diff --git a/src/https.rs b/src/https.rs index 1b467c0..148f15a 100644 --- a/src/https.rs +++ b/src/https.rs @@ -115,7 +115,7 @@ async fn handle( .to_str()? }; let path = req.uri().path(); - let accept_encoding = accept_encoding_fork::parse(req.headers()).unwrap_or(None); + let accept_encoding = accept_encoding_fork::encodings(req.headers()).unwrap_or(vec![]); let best_match = proxy_config .entries @@ -179,11 +179,29 @@ async fn handle( fn try_compress( response: Response<Body>, - accept_encoding: Option<Encoding>, + accept_encoding: Vec<(Option<Encoding>, f32)>, https_config: &HttpsConfig, ) -> Result<Response<Body>> { - // Check if a compression encoding is accepted - let encoding = match accept_encoding { + let max_q: f32 = accept_encoding + .iter() + .max_by_key(|(_, q)| (q * 10000f32) as i64) + .unwrap_or(&(None, 1.)) + .1; + let preference = [ + Encoding::Zstd, + Encoding::Brotli, + Encoding::Deflate, + Encoding::Gzip, + ]; + let encoding_opt = accept_encoding + .iter() + .filter(|(_, q)| *q == max_q) + .filter_map(|(enc, _)| *enc) + .filter(|enc| preference.contains(enc)) + .min_by_key(|enc| preference.iter().position(|x| x == enc).unwrap()); + + // If preferred encoding is none, return as is + let encoding = match encoding_opt { None | Some(Encoding::Identity) => return Ok(response), Some(enc) => enc, }; @@ -197,7 +215,11 @@ fn try_compress( match response.headers().get(header::CONTENT_TYPE) { Some(ct) => { let ct_str = ct.to_str()?; - if !https_config.compress_mime_types.iter().any(|x| x == ct_str) { + let mime_type = match ct_str.split_once(';') { + Some((mime_type, _params)) => mime_type, + None => ct_str, + }; + if !https_config.compress_mime_types.iter().any(|x| x == mime_type) { return Ok(response); } } diff --git a/src/main.rs b/src/main.rs index febe540..ffaa820 100644 --- a/src/main.rs +++ b/src/main.rs @@ -67,7 +67,7 @@ struct Opt { #[structopt( long = "compress-mime-types", env = "TRICOT_COMPRESS_MIME_TYPES", - default_value = "text/html,text/plain,text/css,text/javascript,application/javascript,image/svg+xml" + default_value = "text/html,text/plain,text/css,text/javascript,application/javascript,image/svg+xml,font/ttf" )] pub compress_mime_types: String, } |