Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting Content Length on GZip Requests #9

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 24 additions & 7 deletions src/ring/middleware/gzip.clj
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
(:import (java.util.zip GZIPOutputStream)
(java.io InputStream
OutputStream
ByteArrayOutputStream
ByteArrayInputStream
Closeable
File
PipedInputStream
Expand Down Expand Up @@ -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]
Expand Down