Gzipping in Pedestal + Jetty 9.3

There is a sample in the Pedestal repo for how to get responses gzip compressed by using the GzipFilter from Jetty 9.2. This filter has, however, been removed in Jetty 9.3 and perhaps you want to upgrade to Jetty 9.3 for example to be able to support HTTP/2. It could also be because you use lein-ancient and got Jetty 9.3 unintentionally, what do I know? :-)

Instead of the GzipFilter, Jetty 9.3 supplies a GzipHandler, which can be applied in a similar fashion as adding a filter. Get started by adding these dependencies (possibly of a later version) to your project.clj:

    [org.eclipse.jetty/jetty-server "9.3.0.RC1"]
    [org.eclipse.jetty/jetty-servlet "9.3.0.RC1"]

Then add this import to your service namespace:

    (:import [org.eclipse.jetty.server.handler.gzip GzipHandler])

Just as in the sample with GzipFilter we will use the possibility to “inject” a configuration function that will get a ServletContextHandler as input, which can be manipulated to configure Jetty. Add this to your service-map:

    ::bootstrap/container-options {:context-configurator context-configurator}

…and define a function like this:

    (defn context-configurator
      (let [gzip-handler (GzipHandler.)]
        (.setExcludedAgentPatterns gzip-handler (make-array String 0))
        (.setGzipHandler context gzip-handler))

The setExcludedAgentPatterns makes it possible to exclude certain browsers from receiving gzipped responses. By default IE 6 is excluded, because it apparently doesn’t handle this very well. Excluding user agents, however, has the side effect of adding User-Agent to the Vary response header, which should be avoided (for caching reasons) if not necessary. You might also want to configure for example which methods to include (only GET by default) and which mime types to exclude.

That’s it! Now your Pedestal + Jetty 9.3 server should serve gzipped responses.

This Post Has One Comment

  1. Williamquer

    This paragraph is related to web programming is in fact pleasant in favor of me because I am web programmer. Thanks for sharing keep it up.

Leave a Reply