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).
![](/var/linux_magazin/storage/images/issues/2014/163/clojure/figure-4/616156-1-eng-US/Figure-4_large.png)
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
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.
![Learn More](https://www.linux-magazine.com/var/linux_magazin/storage/images/media/linux-magazine-eng-us/images/misc/learn-more/834592-1-eng-US/Learn-More_medium.png)
News
-
NVIDIA Released Driver for Upcoming NVIDIA 560 GPU for Linux
Not only has NVIDIA released the driver for its upcoming CPU series, it's the first release that defaults to using open-source GPU kernel modules.
-
OpenMandriva Lx 24.07 Released
If you’re into rolling release Linux distributions, OpenMandriva ROME has a new snapshot with a new kernel.
-
Kernel 6.10 Available for General Usage
Linus Torvalds has released the 6.10 kernel and it includes significant performance increases for Intel Core hybrid systems and more.
-
TUXEDO Computers Releases InfinityBook Pro 14 Gen9 Laptop
Sporting either AMD or Intel CPUs, the TUXEDO InfinityBook Pro 14 is an extremely compact, lightweight, sturdy powerhouse.
-
Google Extends Support for Linux Kernels Used for Android
Because the LTS Linux kernel releases are so important to Android, Google has decided to extend the support period beyond that offered by the kernel development team.
-
Linux Mint 22 Stable Delayed
If you're anxious about getting your hands on the stable release of Linux Mint 22, it looks as if you're going to have to wait a bit longer.
-
Nitrux 3.5.1 Available for Install
The latest version of the immutable, systemd-free distribution includes an updated kernel and NVIDIA driver.
-
Debian 12.6 Released with Plenty of Bug Fixes and Updates
The sixth update to Debian "Bookworm" is all about security mitigations and making adjustments for some "serious problems."
-
Canonical Offers 12-Year LTS for Open Source Docker Images
Canonical is expanding its LTS offering to reach beyond the DEB packages with a new distro-less Docker image.
-
Plasma Desktop 6.1 Released with Several Enhancements
If you're a fan of Plasma Desktop, you should be excited about this new point release.