Skip to content

Using Compojure in the projectλ︎

The Compojure defroute function provides a syntax for defining routes and associating handlers.

Ring - adding defroutes to manage routes

Add Compojure to the namespaceλ︎

Add the defroutes function, GET protocol and notfound route from Compojure to the namespace

(ns todo-list.core
  (:require [ring.adapter.jetty :as jetty]
            [ring.middleware.reload :refer [wrap-reload]]
            [compojure.core :refer [defroutes GET]]
            [compojure.route :refer [not-found]]))

Refactor the welcome function to just say Helloλ︎

The welcome function should just do one simple thing, return a welcome message.

(defn welcome
  "A ring handler to respond with a simple welcome message"
  [request]
  {:status 200
     :body "<h1>Hello, Clojure World</h1>
     <p>Welcome to your first Clojure app, I now update automatically</p>"
     <p>I now use defroutes to manage incoming requests</p>
   :headers {}})

Add a defroutes functionλ︎

Add a defroutes function called app to manage our routes. Add routes for / and send all other requests to the Compojure not-found function.

(defroutes app
  (GET "/" [] welcome)
  (not-found "<h1>This is not the page you are looking for</h1>
              <p>Sorry, the page you requested was not found!</p>"))

Update -dev-main and -main functionsλ︎

Change the -dev-main and -main functions to call the app function, instead of the welcome function

(defn -main
  "A very simple web server using Ring & Jetty"
  [port-number]
  (webserver/run-jetty app
     {:port (Integer. port-number)}))

(defn -dev-main
  "A very simple web server using Ring & Jetty that reloads code changes via the development profile of Leiningen"
  [port-number]
  (webserver/run-jetty (wrap-reload #'app)
     {:port (Integer. port-number)}))

As we have changed the -dev-main and -main functions, we need to restart the server again - Ctrl-c then lein run 8000

Now test out your updated web app by visiting http://localhost:8000 and http://localhost:8000/not-there