index : static-web-server.git

ascending towards madness

author Jose Quintana <joseluisquintana20@gmail.com> 2020-05-08 1:16:53.0 +00:00:00
committer Jose Quintana <joseluisquintana20@gmail.com> 2020-05-08 1:16:53.0 +00:00:00
commit
4bda5f3280b387810c84fed7df5910544077ab6d [patch]
tree
6ddd254a5bb85179fe7e88bef74b279f06adfff2
parent
7a0fed08fd32f65f67bded2cf66f1de138813ef9
download
4bda5f3280b387810c84fed7df5910544077ab6d.tar.gz

refactor: simplify gzip middleware



Diff

 src/gzip.rs | 44 ++++----------------------------------------
 1 file changed, 4 insertions(+), 40 deletions(-)

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

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
@@ -34,27 +15,10 @@ impl AfterMiddleware for GzipMiddleware {
        }

        // 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,
        };
        let enable_gz = helpers::is_text_mime_type(resp.headers.get::<ContentType>());
        let accept_gz = helpers::accept_gzip(req.headers.get::<AcceptEncoding>());

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