2009-06-09

Basic Compojure Calculator

Compojure turned out to be relatively simple for making a basic URL driven calculator. Go to a URL like http://localhost:8080/add/4/5 and you get a page that simply says, "9". The Compojure documentation isn't complete yet (the site is quite upfront about that, and honesty is always nice), but along with examples online, there's probably enough to make a real web app. The full code is at the end of the post, but first I'll try to explain the code section by section.

(use 'compojure)
Gives the defroute thing (function or macro? I still get them confused) that we'll need later.

(def op-mapping
{"add" +,
"subtract" -,
"multiply" *,
"divide" /})

Obviously this just makes a hash mapping the English name for an operator to the actual function. The English names are what are used in the URL.

(defn doop [op ls rs]
"Do the operation on the two values"
(if (contains? op-mapping op)
(str ((get op-mapping op) ls rs))
"Unrecognized operation"))

Looks for the operation in the map, return an error if it can't be found. Otherwise run the function it maps to on the two given values. Nothing is Compojure specific yet.

(defroutes calc
(GET "/:op/:ls/:rs" (doop (params :op) (. Float valueOf (params :ls)) (. Float valueOf (params :rs))))
(ANY "/*" "Bad URL"))

This is the first chunk of Compojure specific code. All it does is define a route, the URL to what-do-you-want-to-do mapping. The first GET definition is a pretty neat way of specifying parameters. The pattern is given "/:op/:ls/:rs" and then the route parameters are available later with (params :op) and the like. Makes it easy to parse things out and you don't have to number everything.

(run-server {:port 8080}
"/*" (servlet calc))

The last chunk of Compojure specific code. Also the last chunk of the web app. It just starts up the web server and points it to the route chains.

Every small chunk was simple, clear, and had a specific useful purpose. Overall, the web framework is looking good so far. I think I'll keep experimenting with it.

Now for the full code:
(use 'compojure)

;;; Available operations
(def op-mapping
{"add" +,
"subtract" -,
"multiply" *,
"divide" /})

(defn doop [op ls rs]
"Do the operation on the two values"
(if (contains? op-mapping op)
(str ((get op-mapping op) ls rs))
"Unrecognized operation"))

(defroutes calc
(GET "/:op/:ls/:rs" (doop (params :op) (. Float valueOf (params :ls)) (. Float valueOf (params :rs))))
(ANY "/*" "Bad URL"))

(run-server {:port 8080}
"/*" (servlet calc))

1 comment:

Anonymous said...

Thank you much, for me, this is very clear and the only understandable tutorial I've seen on compojure on the web.