Building a simple HTTP server in Clojure: Part I — Setting up server
In my previous post I discussed about my experience with Clojure. This blog will focus on how to build a very basic HTTP server which will display local time whenever hit.
This should take utmost 5 min to bring the server up (if Clojure and Leiningen is already setup).
Basic Setup
I use leiningen to set-up and run Clojure project. Here is a detailed tutorial to setup Leiningen and start with development:
Once the setup is done, we can proceed further to start with Clojure HTTP Server.
Getting Started
We shall be creating a new project using lein:
lein new clojure-simple-http
The above command makes a new project clojure-simple-http with the following structure
.
├── CHANGELOG.md
├── LICENSE
├── README.md
├── doc
│ └── intro.md
├── project.clj
├── resources
├── src
│ └── clojure_simple_http
│ └── core.clj
└── test
└── clojure_simple_http
└── core_test.clj
Dependencies
We are using http-kit library, so we need to add this as a dependency in our project.clj. It will look something like this:
Also core.clj will contain main function, so we define the file where main will be present in project.clj too.
Creating Server
I have used the default code from http-kit-server to create bare minimum server. We make the changes in core.clj. This file shall also contain the main function to start the server.
We first need to require http-kit library
(:require [org.httpkit.server :refer [run-server]])
The final code will look like this:
The response of request is a map with status, headers and body.
Display Current Time (Local)
To display current time we shall use clj-time library of clojure.
Firstly we need to add it to the dependency in project.clj as [clj-time “0.14.0”] and import [clj-time.core :as t] in core.clj
Then to return the time, we use time-now function which returns time object. So we convert it to string using (str (t/time-now))
which returns time in correct format.
Final Run
Now goto the directory and do lein run
. This will start the server on port 8080.
Tada! We made a very simple server in Clojure.
The complete code can be found on Github.
In my next blog I shall be focussing on how to add routing to the server using compojure and how to dockerize the app.
If you have any questions/suggestions, feel free to drop it in comments and if you found this article useful, clap below.