clojurecompojurering

Add middleware to default Compojure project


I have worked with the Compojure Leiningen template with my code but now I'm struggling to add middleware. For reference, this is the default project:

(ns test.handler
  (:require [compojure.core :refer :all]
            [compojure.route :as route]
            [ring.middleware.defaults :refer [wrap-defaults site-defaults]]))

(defroutes app-routes
  (GET "/" [] "Hello World")
  (route/not-found "Not Found"))

(def app
  (wrap-defaults app-routes site-defaults))

My code functionally doesn't deviate from this.
I would like to add the [bk/ring-gzip "0.3.0"] middleware. I understand the concept but I haven't been able to find the syntax which extends this configuration.

Thank you for your time!


Solution

  • The example on the bk/ring-gzip site just needs adapting slightly. The routes returned from compojure are a handler; the wrappers take a handler and return a handler. If you need other handlers they should be before gzip if they act on the request or response bodies.

    (def app (-> app-routes
        (wrap-defaults site-defaults)
        (wrap-gzip)))
    

    It's normally preferred to use the threading macro form as you may have several middlewares to compose, but you could just call functions.