Tech behind Tech

Raw information. No finesse :)

Compojure Demystified with an example – Part 5

with 2 comments

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)

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

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.

Written by Siva Jagadeesan

September 2, 2010 at 12:19 am

Posted in Clojure

Tagged with , , , , ,

2 Responses

Subscribe to comments with RSS.

  1. Hi Siva

    thanks again for your post.
    For the french speakers interested in it I’ve updated my translation (

    — Ben


    September 2, 2010 at 2:31 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: