Skip to content

Instantly share code, notes, and snippets.

@abp
Forked from weavejester/gist:3694454
Created September 11, 2012 11:10
Show Gist options
  • Save abp/3697650 to your computer and use it in GitHub Desktop.
Save abp/3697650 to your computer and use it in GitHub Desktop.
;; A basic Ring handler
(defn handler [request]
{:status 200
:headers {}
:body "Hello World"})
;; Which can also be written:
(def handler
(fn [request]
{:status 200
:headers {}
:body "Hello World"}))
;; A Ring handler that return nil if request doesn't match:
(def my-route
(fn [request]
(if (and (= (:request-method request) :get)
(= (:uri request) "/"))
{:status 200
:headers {}
:body "Hello World"})))
;; Pretty verbose, right? Compojure can make things more concise:
(def my-route
(GET "/" []
{:status 200
:headers {}
:body "Hello World"}))
;; It's still the same code underneath, though! GET returns a function.
;; Compojure will also fill in the :status 200 and :headers if you return a string:
(def my-route
(GET "/" [] "Hello World"))
;; Still the same result, though!
;; What if you want to match multiple functions?
(def route-a
(GET "/hi" [] "Hello World"))
(def route-b
(GET "/bye" [] "Goodbye World"))
;; We can combine them with if statements:
(def combined-routes
(fn [request]
(let [response-a (route-a request)]
(if response-a
response-a
(route-b request)))))
;; Or just with an "or":
(def combined-routes
(fn [request]
(or (route-a request)
(route-b request))))
;; Remember "or" will keep evaluating until it finds a "true" value; that means anything
;; which isn't nil or false.
;; Compojure makes this even more concise with "routes":
(def combined-routes
(routes route-a route-b))
;; Again, it's the same as above, just written more concisely.
;; And we can use defroutes to shorten (def ... (routes ...)) in the same way
;; we can use defn to shorten (def ... (fn ...))
(defroutes combined-routes
route-a route-b)
;; Almost there!
;; So we have our combined routes, but why bother defining route-a and route-b? We can go inline:
(defroutes combined-routes
(GET "/hi" [] "Hello World")
(GET "/bye" [] "Goodbye World"))
;; And because the output from "routes" is just a function, we can nest routes within routes:
(defroutes main-routes
(GET "/" [] "Index")
combined-routes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment