If you read my last Compojure post, you will soon discover (like me) that you need to put in a little bit more work to get a practical setup. Thanks to arbscht in #compojure for showing me all of this.
So first up you need to create a new Leiningen project. Luckily there’s an inbuilt command to help.
Now you should be able to see the skeleton of your new project. Next, you need to set up the
project.clj file, it’s used to set the name and dependencies for the project.
You will need to add a description, adjust the version and add the required dependencies for a Compojure based website. Here’s what an example:
Now inside ./src/example/ we need to create a
server.clj file that we can use to setup the web server, here’s mine:
Three interesting things to note with that example:
- We put the
run-jettycall inside a function. That way when the file is included the server doesn’t automatically start. Inconvenient but it lets us
:reloadthe file as much as we need.
- We pass
#'main-routesinstead of just
main-routes, that is so that any changes to our routes are put in effect as soon as the
(defroutes main-routes ...)s-exp is re-evaled.
- The page /test/* is going to display “Hello *” as an example of how to capture “parameters” from the user. Try just passing
(:name (:params req))to see what else is available to you.
Now we are ready to give this a go, make sure you’re in the root of your project and type:
To start a Clojure process for your project that also runs a Swank server. Then you need to open Emacs and do the following:
Now browse to http://localhost:8080, and you should see a “Hello world” page. Browse to http://localhost:8080/test/Dave, and it should say “Hello Dave”. Finally, change your server.clj to say “Hello new world” and re-eval the
(defroutes ...). The change should take effect as soon as you refresh your browser!