Writing web applications in Clojure
Mutable
The atom accomplishes yet another feat: Immutable data structures in functional languages can be stored in mutable containers. Normally, functions only return updated copies of a data structure, such as the vector v
in the following interactive session.
The function conj
adds another element – it just copies the output – and the original vector remains unchanged:
webapp.core=> (def v [1 2]) #'webapp.core/v webapp.core=> v [1 2] webapp.core=> (conj v 3) [1 2 3] webapp.core=> v [1 2]
If you choose to include a vector or set in an atom, you can use it as a variable data collection with guaranteed exclusive access:
webapp.core=> (def a (atom [1 2])) #'webapp.core/a webapp.core=> a #<Atom@320bdadc: [1 2]> webapp.core=> (swap! a conj 3) [1 2 3] webapp.core=> a #<Atom@320bdadc: [1 2 3]>
The code within the let
expression (Listing 8, line 39) calls the wrap-params
function with a return value of routes
. Two routes can be seen in routes
. The first is not a call to the root
function because this would be (root)
in Clojure. Instead, it is passed by value. Ring takes care of the call, passing in the HTTP request as an argument.
What is new is the second route, which serves the path to "/ws"
. It is defined as the return value of the websocket
function with the channels
argument. As can be seen in the function body (line 26), it returns a function that takes an incoming HTTP request as an argument. It extracts name
from the parameter list. In the next step, http/with-channel
binds channel
to an asynchronous channel, which should be a WebSocket connection. If it is not, the application returns an error and sets the HTTP status 426 Upgrade Required
(Figure 3).
If successful, the code passes the channel on to the new-client
function, together with the name
parameter and the channels
atom. As the name implies, new-client
(line 16) is responsible for newly established connections. The function first calls swap!
with the channels
atom as its argument. swap!
applies the remaining arguments to the values in the atom and replaces its content with the results.
The new value in the atom is (conj previous-value channel)
– that is, the set of existing connections plus the new one. This is followed by the doto
block defining two handlers for the channel. On closing the channel (http/on-close
), swap!
is again used, but this time with disj
, which in contrast to conj
, removes an element from the set of channels
. The application then sends a broadcast to the rest of the channels that a conversation participant has dropped out.
Paging All Users
On receiving (http/on-receive
) a new message, the program simply sends it to all the clients. In the last step, new-client
announces the arrival of a new participant.
The broadcast
function itself is also worth a look (Listing 8, line 11). It takes two arguments, the atom with all the channels, and a string to be sent as a message. Using deref
, it extracts the set with the channels from the channels
atom. It then iterates over all channels and uses the http/send!
function to transmit the message to each channel.
If you are getting restless and want to start the application, be patient and just take a look at the remaining two files. Listing 9 (src/webapp/main.clj
) contains a small namespace that helps start the application. It integrates the HTTP server and the app
from webapp.core
.
Listing 9
src/webapp/main.clj
The -main
function is equivalent to the main
method in the Java world – it fires up when the application is called at the command line, starts the server, and outputs a brief status message. The :gen-class
keyword in the namespace causes the compiler to compile a Java class from webapp.main
.
Finally, Listing 10 is the Enlive template. It contains HTML and a little JavaScript to open the WebSocket connections in the browser and encode HTML special characters.
Listing 10
resources/templates/index.html
If you now launch the application with lein run
, it calls the -main
function in the main
namespace. Instead of calling the server from the project directory, you can bundle the whole application into a JAR archive, which is suitable for deployment or distributing to customers. It contains everything the webchat needs. The Leiningen lein uberjar
command handles this. The resulting jar archive only requires a Java run time and can be run by typing java -jar <archive name.jar>
(Figure 4).

The Future
Once you have grown accustomed to the Clojure syntax and to working in REPL, web applications are relatively easy to implement with Leiningen and a handful of libraries. For web developers, templating systems such as Hiccup [11] and Enlive [12] are important, but they represent only a fraction of the Clojure ecosystem. If you want to know more about Clojure, various books about the programming language are available on the market [13]. If you need to practice, you can go to the 4Clojure [14] website for a large collection of programming tasks. Finally, the blog aggregator, Planet Clojure [15], groups what's new in the Clojure community.
Infos
- Clojure: http://clojure.org
- Clojure user groups: http://dev.clojure.org/display/community/Clojure+User+Groups
- Clojure West: http://www.clojurewest.org/
- Clojure/conj: http://clojure-conj.org/
- Stefan Kamphausen, "Concurrency": Linux-Magazin 01/10, p. 112; http://www.linux-magazin.de/Ausgaben/2010/01/Nebenlaeufig [in German]
- "Beating the Averages" by Paul Graham, http://www.paulgraham.com/avg.html
- Leiningen: https://github.com/technomancy/leiningen
- Listings for this article: ftp://ftp.linux-magazin.com/pub/listings/magazine/163
- Compojure on GitHub: https://github.com/weavejester/compojure
- Httpkit: http://http-kit.org
- Hiccup: https://github.com/weavejester/hiccup
- Enlive: https://github.com/cgrand/enlive
- Books about Clojure: http://clojure.org/books
- Programming tasks: http://4clojure.com
- Planet Clojure: http://planet.clojure.in
« Previous 1 2 3
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
Direct Download
Read full article as PDF:
Price $2.95
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
Support Our Work
Linux Magazine content is made possible with support from readers like you. Please consider contributing when you've found an article to be beneficial.
News
-
Armbian 23.05 is Now Available
Based on Debian 12, the latest version of the ARM/RISC-V distribution is now available to download and install.
-
Linux Mint Finally Receiving Support for Gestures
If you use the Linux Mint Cinnamon desktop, you'll be thrilled to know that 21.2 is getting support for gestures on touchscreen devices and touchpads.
-
An All-Snap Version of Ubuntu is In The Works
Along with the standard deb version of the open-source operating system, Canonical will release an-all snap version.
-
Mageia 9 Beta 2 Ready for Testing
The latest beta of the popular Mageia distribution now includes the latest kernel and plenty of updated applications.
-
KDE Plasma 6 Looks to Bring Basic HDR Support
The KWin piece of KDE Plasma now has HDR support and color management geared for the 6.0 release.
-
Bodhi Linux 7.0 Beta Ready for Testing
The latest iteration of the Bohdi Linux distribution is now available for those who want to experience what's in store and for testing purposes.
-
Changes Coming to Ubuntu PPA Usage
The way you manage Personal Package Archives will be changing with the release of Ubuntu 23.10.
-
AlmaLinux 9.2 Now Available for Download
AlmaLinux has been released and provides a free alternative to upstream Red Hat Enterprise Linux.
-
An Immutable Version of Fedora Is Under Consideration
For anyone who's a fan of using immutable versions of Linux, the Fedora team is currently considering adding a new spin called Fedora Onyx.
-
New Release of Br OS Includes ChatGPT Integration
Br OS 23.04 is now available and is geared specifically toward web content creation.