From 0aea6af9259ebac67692715a192843c852266549 Mon Sep 17 00:00:00 2001 From: Tejas Dinkar Date: Fri, 28 Oct 2016 17:27:31 +0530 Subject: [PATCH 1/2] Setting Content Length on GZip Requests This adds a Content-Length to the response, if an original Content-Length was present, and less than 1MB. This prevents jetty from adding Transfer-Encoding: chunked to the response, without requiring Connection: Close --- src/ring/middleware/gzip.clj | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/src/ring/middleware/gzip.clj b/src/ring/middleware/gzip.clj index ec2bee4..0ea70d6 100644 --- a/src/ring/middleware/gzip.clj +++ b/src/ring/middleware/gzip.clj @@ -4,6 +4,8 @@ (:import (java.util.zip GZIPOutputStream) (java.io InputStream OutputStream + ByteArrayOutputStream + ByteArrayInputStream Closeable File PipedInputStream @@ -52,13 +54,28 @@ (.close ^Closeable in))) pipe-in)) -(defn gzipped-response [resp] - (-> resp - (update-in [:headers] - #(-> % - (assoc "Content-Encoding" "gzip") - (dissoc "Content-Length"))) - (update-in [:body] piped-gzipped-input-stream))) +(defn- gzip-into-byte-array? [resp] + (if-let [length (get-in resp [:headers "Content-Length"])] + (< (Long/parseLong length) 1048576))) + +(defn gzipped-response [{:keys [body] :as resp}] + (let [gzip-body (piped-gzipped-input-stream body)] + (if (gzip-into-byte-array? resp) + (let [output-stream (ByteArrayOutputStream.) + _ (-> (io/copy gzip-body output-stream)) + gzip-bytes (.toByteArray output-stream)] + (-> resp + (update-in [:headers] + #(-> % + (assoc "Content-Encoding" "gzip") + (assoc "Content-Length" (str (count gzip-bytes))))) + (assoc :body (ByteArrayInputStream. gzip-bytes)))) + (-> resp + (update-in [:headers] + #(-> % + (assoc "Content-Encoding" "gzip") + (dissoc "Content-Length"))) + (assoc :body gzip-body))))) (defn wrap-gzip [handler] (fn [req] From 1772449a43ed02cd8beaf93b8206acbb64f84765 Mon Sep 17 00:00:00 2001 From: Tejas Dinkar Date: Sun, 30 Oct 2016 08:08:59 +0530 Subject: [PATCH 2/2] Removing uneccesary thread --- src/ring/middleware/gzip.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ring/middleware/gzip.clj b/src/ring/middleware/gzip.clj index 0ea70d6..6a7cabb 100644 --- a/src/ring/middleware/gzip.clj +++ b/src/ring/middleware/gzip.clj @@ -62,7 +62,7 @@ (let [gzip-body (piped-gzipped-input-stream body)] (if (gzip-into-byte-array? resp) (let [output-stream (ByteArrayOutputStream.) - _ (-> (io/copy gzip-body output-stream)) + _ (io/copy gzip-body output-stream) gzip-bytes (.toByteArray output-stream)] (-> resp (update-in [:headers]