Cogs and Levers A blog full of technical stuff

Compojure

In a previous post, we setup a really simple route and server executing some Clojure code for us. In today’s post, we’re going to use a library called Compojure to fancy-up a little bit of that route definition.

This should make defining our web application a bit more fun, anyway.

Getting started

Again, we’ll use Leiningen to kick our project off:

lein new webapp-1

We’re going to add some dependencies to the project.clj folder for compojure and http-kit. http-kit is the server that we’ll be using today.

(defproject webapp-1 "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.8.0"]
           [compojure "1.1.8"]
           [http-kit "2.1.16"]])

And then, installation.

lein deps

Hello!

To get started, we’ll define a root route to greet us.

(ns webapp-1.core
  (:require [compojure.core :refer :all]
        [org.httpkit.server :refer [run-server]]))

(defroutes greeter-app
  (GET "/" [] "Hello!"))

(defn -main []
  (run-server greeter-app {:port 3000}))

A quick hit through curl lets us know that we’re up and running:

curl --verbose localhost:3000
* Rebuilt URL to: localhost:3000/
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET / HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.47.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: text/html; charset=utf-8
< Content-Length: 6
< Server: http-kit
< Date: Thu, 17 Nov 2016 02:42:48 GMT
< 
* Connection #0 to host localhost left intact
Hello!

Check out the following:

Good fun.