In today’s post, we’re going to use the Clojure HTTP server abstraction called ring to stand a web server up, and attach some some routes. This allows us to expose our Clojure functions over the web in a relatively simple fashion.
Getting started
This blog post is mainly centered around the getting started guide from the ring documentation pages, found here.
We’re going to get started by creating a project using lein.
After this process finishes, you’ll end up with a directory called jetty-test that has a project structure something like this:
Dependencies
Now we need to make our newly created project depend on ring. We need to add references to ring-core and ring-jetty-adapter in the project.clj file. So it should read something like this:
We can now install these dependencies into the project.
Server code
We can start writing our route code now that the server will respond to. We’ll define a function that simply returns the current date and time:
We’ll also create a route that will use this function, and send back the text each time the route is requested:
That’s it for the server code. We still need to fire up Jetty and attach the handler to it. We need to import ring.adapter.jetty as it contains run-jetty for us:
Running
We run our project using lein:
Our output now looks something like this:
. . . suggesting that our server is ready to take requests. We can use curl to test it out for us: