Writing web applications in Clojure


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
[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
#<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).

Figure 3: The /ws path is reserved for WebSockets; otherwise, the chat application complains.

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



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



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).

Figure 4: Leiningen packs the entire application, including the libraries, into an executable JAR archive.

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.

The Author

Jan Stepien works as a developer at Stylefruits.de and as a coach with Clojureworkshop.de. He studied at the Warsaw University of Technology, is a fan of Clojure and Haskell, and enjoys mountaineering. He tweets @janstepien.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

comments powered by Disqus

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.