Compression

plumeria.gzip/wrap-gzip is Ring middleware that gzips a response when the client accepts it. Wrap the handler, or one route, and pass an options map if the defaults don't fit:

(require '[plumeria.gzip :as gzip])

(gzip/wrap-gzip handler)
(gzip/wrap-gzip handler {:min-size 1024                     ; bytes, for a String or byte[] body
                         :compressible? gzip/compressible?  ; a fn of the Content-Type
                         :compress? (fn [req resp] true)})  ; per-response opt-out

It compresses text/*, JSON, JavaScript, XML, any +json or +xml type and SVG, whatever the body is except a File. A String or byte[] stays a buffered body with a Content-Length, and is skipped below :min-size. An InputStream or a seq becomes a compressing InputStream. A :stream fn is wrapped so that every write is compressed and flushed straight away, which means an SSE stream still delivers each event as it's sent. Nothing is compressed for a 206, a 204 or 304, a response that already has a Content-Encoding, or one whose Cache-Control says no-transform.

A compressed response gets Content-Encoding: gzip and Vary: Accept-Encoding, loses its Content-Length, and has -gz added to its ETag ("v1" becomes "v1-gz"), since the zipped bytes are a different entity. Revalidation still works: the middleware strips the -gz from If-None-Match and If-Match before your handler sees them, and a 304 answering a -gz tag gets the -gz back. Ring's wrap-not-modified works on either side of it.

BREACH. Don't compress a response that holds a secret, such as a session or CSRF token, and text the visitor controls, such as an echoed search term. An attacker who can make the victim's browser send requests can recover the secret from the compressed sizes, through TLS too. The middleware can't tell such a response apart from any other, so answer false from :compress? for it, or leave that route unwrapped.

Compression has a CPU price. On loopback a 12.8 KB JSON page, compressed to 1,317 bytes, ran at half to two thirds of its uncompressed rate (see performance.md). On a real network the smaller response usually matters more.