Compojure Demystified with an example – Part 5
In this part lets write our own middleware.
From part4 you will remember,
“Middleware are functions that could be chained together to process a request. Middleware functions can take any number of arguments, but the spec stats that first argument should be a handler and function should return a handler. An example for middleware is logging all requests that comes to your webserver.”
1) Create a namespace for middleware
Create src/address_book/middleware.clj
(ns address-book.middleware)
(defn- log [msg & vals]
(let [line (apply format msg vals)]
(locking System/out (println line))))
(defn wrap-request-logging [handler]
(fn [{:keys [request-method uri] :as req}]
(let [resp (handler req)]
(log "Processing %s %s" request-method uri)
resp)))
Our wrap-request-logging is a middleware which takes a handler and returns an handler.
2) Add our middleware to our chain of handlers
Edit routes.clj
(ns address_book.routes
(:use [compojure.core])
(:require [address-book.address :as address]
[address-book.middleware :as mdw]
[compojure.route :as route]
[clj-json.core :as json]))
(defn json-response [data & [status]]
{:status (or status 200)
:headers {"Content-Type" "application/json"}
:body (json/generate-string data)})
(defroutes handler
(GET "/addresses" [] (json-response (address/find-all)))
(GET "/addresses/:id" [id] (json-response (address/find id)))
(POST "/addresses" {params :params} (json-response (address/create params)))
(route/files "/" {:root "public"})
(route/not-found "Page not found"))
(def address-book
(-> handler
mdw/wrap-request-logging))
3) Test our middleware
Now start your server and you can see all requests are getting logged. This is very powerful feature. We can do security etc using middleware. Ring and Compojure comes with some useful middleware. Check them out.
In next part we will implement edit and delete functionalities.
Source code is now available at github. Created branches for each part.

Hi Siva
thanks again for your post.
For the french speakers interested in it I’ve updated my translation (http://bao.maleloria.org/misc/compojure-demystifie.html).
— Ben
Ben
September 2, 2010 at 2:31 pm
Thanks, Ben.
Siva Jagadeesan
September 2, 2010 at 2:50 pm