Search This Blog

Wednesday, March 17, 2010

Clojure, Maven, Emacs, Compojure: Hello Web.

Let's use maven to construct a web server:

Take the setup from the last post (http://learnclojure.blogspot.com/2010/03/clojure-maven-emacs-eternal-golden.html),

Paste the snippet


   
    <dependency>
      <groupId>compojure</groupId>
      <artifactId>compojure</artifactId>
      <version>0.3.2</version>
    </dependency>
    

Into the <dependencies> section of the pom.xml file, and then restart clojure using
mvn clojure:repl or mvn clojure:swank, according to taste.

Maven will again appear to download the internet as it goes and pulls in compojure and all its dependencies.

If you're using emacs, then when the swank server restarts, connect with M-x slime-connect.

At the REPL prompt, try


user> (use 'compojure)
nil
user> (defn yo "yo")
#'user/yo
user> (defroutes my-app (GET "/" yo))
#'user/my-app
user> (run-server {:port 8080} "/*" (servlet my-app))
user.proxy$javax.servlet.http.HttpServlet$0
#<Server Server@a16605>

And you are totally running a web server. Go check it out at http://localhost:8080.

OK, it's not brilliant. Somewhere in the carnage it should say:

Wrong number of args passed to: user$yo

We can fix that:

user> (defn yo [s] "yo")
#'user/yo

Now have another look.

user> (defn yo [s] (html [:h1 "yo"]))
#'user/yo


And finally let's get all standards-compliant:

user> (defn yo [s]
        (html
         [:head
          [:title "hello world"]]
         [:body
          [:h1 "yo"]]))
#'user/yo


So loading a library, itself with many dependencies, and setting up the relevant classpath, are reduced to the finding of one xml snippet.

Once we've done that we can run a process which both serves web pages and runs a swank server that allows us to modify its code as it's running, without restarting anything.

Many clojure library snippets can be found at http://clojars.org.
There are various modified versions of compojure there, which will be found by a search for compojure. The canonical version is at http://clojars.org/compojure.

3 comments:

Followers