Building a simple HTTP server in Clojure: Part II — Adding routes

Divyum Rastogi
1 min readSep 30, 2017

--

In the Part I of blog, I discussed about setting up a simple server but what use it is when there is no routing. So continuing the server journey, I shall discuss how to add routing to your server.

I shall be use compojure library to serve the purpose. I would highly recommend to go through Part I of the blog.

Dependencies

We need to add [compojure "1.6.0"] as routing dependency in project.clj.
It will look something like this:

Add Route

To add route, we need to import compojure.core and compojure.route in core.clj. We also define a function which will return the time as response. Below is the complete file:

compojure provides a macro defroutes which is used to define routes.

What is a macro?
Macro is a tool that allows compiler to be extended by user code. It is more like a function which can be used to reduce multiple set of repeating instructions into a single statement but the difference is in execution method. Read more about it here.

The function get-time is called when request hits /get-time route. The function returns a map as response.

Compojure also provides not-found route which is when none of the routes match.

The complete code is on Github.

Thus, we have server ready with routes. Now we can run the server as discussed before.

If you have any questions/suggestions, feel free to drop it in comments and if you found this article useful, clap below.

--

--