Saturday 3 October 2015

Build the simplest possible http-kit app

In an attempt to get as bare metal as possible with some clojure web stuff, I wanted to make the most bare bones http-kit application to familiarise myself how things wire together. I’m going to call this application simple. You will need leiningen installed. A lot of this code is copied verbatim from the http-kit site so that you can see for yourself how it all fits together.

Project Structure

I’ve always used leinegen to start projects, but for this app I’m going to do this manually …

mkdir simple
cd simple
mkdir -p  src/simple/
touch src/simple/core.clj

Open up project.clj and edit it so that it matches the following. Watch out for typos

(defproject simple "0.0.0-SNAPSHOT"
  :dependencies [[org.clojure/clojure "1.7.0"]
                 [http-kit "2.1.19"]])

At this point you can now run lein repl, you will notice that leinigen creates a load of directories for you and loads up your repl and you may also notice that some dependancies are installed (dont worry if they are not as this means you already have them). This is not very useful yet, but you can leave the repl running whilst you create the next file.

Next open up src/simple/core.clj and edit it so that it matches the following …

(ns simple.core
  (:use org.httpkit.server))

(defn app [req]
  {:status  200
   :headers {"Content-Type" "text/html"}
   :body    "hello HTTP!"})

(run-server app {:port 8080})

Go back to the running repl and load up your file

(use 'simple.core :reload)

You can now open up a browser and hit and see your work.

Right now, this application is useless. Go ahead and make a change to core.clj and you’ll see that the change is not reflected when you refresh the page. If you try and reload the file via the repl, you’ll get the following error …

CompilerException Address already in use, compiling:(simple/core.clj:11:1)


Right now, this app is not that great or useful. I’m going to make this application by fiddling with it, in small steps, until I’ve got …

  1. Build the simplest possible http-kit app
  2. App running via lein run and live reloading of source
  3. Logging requests to stdout
  4. Routes with and without parameters
  5. Postgres integration
  6. Writing Tests
  7. Configuring the application to return JSON Responses (coming soon)
  8. A Clojurescript UI (coming soon)
  9. Websockets (coming soon)
  10. Putting your application into production (coming soon)

The full source code can be found on github and I’ve tagged the code for this post as 1.