Setting HTTP server in Clojure

As a learning process, I decided to learn Clojure by finding myself a “project”. By chance, I found out about something called Kennyspeak. It’s a simple (and funny) translator which converts given text to something which Kenny, the guy from South Park, would say.

First, I decided to make a package that translates text to kennyspeak. It’s still rough on the edges and misses some polishing, but hey, it’s done! My next step was to build a React app (with help of Reagent). Unfortunately, there are some things which I yet don’t understand, so I decided to give it some time.

As my next step, I picked up an API which will translate a text. I’m unfamiliar with tooling so it’s a good opportunity to try to document the process. My Clojure journey started with Leiningen so the project will be based on it.

Let’s start with creating a new project:

lein new app kennyfy-api

As a HTTP server I’ll use http-kit. Add it to :dependencies in project.clj:

  :dependencies [[org.clojure/clojure "1.9.0"]
                 [http-kit "2.3.0"]]

For basic things http-kit is pretty simple in use. You need to define a handler and start the server. Handler is a function which accepts a request map and returns a response map.

Now, all you need to do is import run-server from org.httpkit.server and start it in -main function.

(ns kennyfy-api.core
  (:require [org.httpkit.server :refer [run-server]])
  (:gen-class))

(defn handler
  [req]
  {:status 200
   :headers {"Content-type" "text/html"}
   :body "Hello there!"})

(defn -main
  [& args]
  (run-server #'handler {:port 8080})
  (println "Server running on port 8080"))

Now, type lein run in the console. The HTTP server should start listening on port 8080.
That’s it! You’ve set up your first HTTP server in Clojure 🎉