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
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
-
Linux Servers Targeted by Akira Ransomware
A group of bad actors who have already extorted $42 million have their sights set on the Linux platform.
-
TUXEDO Computers Unveils Linux Laptop Featuring AMD Ryzen CPU
This latest release is the first laptop to include the new CPU from Ryzen and Linux preinstalled.
-
XZ Gets the All-Clear
The back door xz vulnerability has been officially reverted for Fedora 40 and versions 38 and 39 were never affected.
-
Canonical Collaborates with Qualcomm on New Venture
This new joint effort is geared toward bringing Ubuntu and Ubuntu Core to Qualcomm-powered devices.
-
Kodi 21.0 Open-Source Entertainment Hub Released
After a year of development, the award-winning Kodi cross-platform, media center software is now available with many new additions and improvements.
-
Linux Usage Increases in Two Key Areas
If market share is your thing, you'll be happy to know that Linux is on the rise in two areas that, if they keep climbing, could have serious meaning for Linux's future.
-
Vulnerability Discovered in xz Libraries
An urgent alert for Fedora 40 has been posted and users should pay attention.
-
Canonical Bumps LTS Support to 12 years
If you're worried that your Ubuntu LTS release won't be supported long enough to last, Canonical has a surprise for you in the form of 12 years of security coverage.
-
Fedora 40 Beta Released Soon
With the official release of Fedora 40 coming in April, it's almost time to download the beta and see what's new.
-
New Pentesting Distribution to Compete with Kali Linux
SnoopGod is now available for your testing needs