index : static-web-server.git

ascending towards madness

author Jose Quintana <joseluisquintana20@gmail.com> 2020-05-03 23:10:51.0 +00:00:00
committer Jose Quintana <joseluisquintana20@gmail.com> 2020-05-03 23:10:51.0 +00:00:00
commit
ed94c4ba0f0fdf2859e44fc3f84bbd8686217d55 [patch]
tree
7c8196eebc6b2bfaceaca26536a514ab97506d65
parent
ec7751749e06a100c6d0dd73e2227c56e1b0b6ca
download
ed94c4ba0f0fdf2859e44fc3f84bbd8686217d55.tar.gz

feat: enable gzip compression only for known text-based file types

resolves #19

Diff

 src/gzip.rs | 41 +++++++++++++++++++++++++++++++++++++++--
 1 file changed, 39 insertions(+), 2 deletions(-)

diff --git a/src/gzip.rs b/src/gzip.rs
index 6675fb4..ca88b41 100644
--- a/src/gzip.rs
+++ b/src/gzip.rs
@@ -1,11 +1,31 @@
use flate2::write::GzEncoder;
use flate2::Compression;
use iron::headers::{AcceptEncoding, ContentEncoding, Encoding};
use iron::headers::{AcceptEncoding, ContentEncoding, ContentType, Encoding};
use iron::mime;
use iron::prelude::*;
use iron::AfterMiddleware;

pub struct GzipMiddleware;

const GZIP_TYPES: [&str; 16] = [
    "text/html",
    "text/css",
    "text/javascript",
    "text/xml",
    "text/plain",
    "text/x-component",
    "application/javascript",
    "application/x-javascript",
    "application/json",
    "application/xml",
    "application/rss+xml",
    "application/atom+xml",
    "font/truetype",
    "font/opentype",
    "application/vnd.ms-fontobject",
    "image/svg+xml",
];

impl AfterMiddleware for GzipMiddleware {
    fn after(&self, req: &mut Request, mut resp: Response) -> IronResult<Response> {
        // Skip Gzip response on HEAD requests
@@ -13,11 +33,28 @@ impl AfterMiddleware for GzipMiddleware {
            return Ok(resp);
        }

        // Enable Gzip compression only for known text-based file types
        let enable_gzip = match resp.headers.get::<ContentType>() {
            Some(content_type) => {
                let mut v = false;
                for e in &GZIP_TYPES {
                    if content_type.0 == e.parse::<mime::Mime>().unwrap() {
                        v = true;
                        break;
                    }
                }

                v
            }
            None => false,
        };

        let accept_gz = match req.headers.get::<AcceptEncoding>() {
            Some(accept) => accept.0.iter().any(|qi| qi.item == Encoding::Gzip),
            None => false,
        };
        if accept_gz {

        if enable_gzip && accept_gz {
            let compressed_bytes = resp.body.as_mut().map(|b| {
                let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
                {