public
Last active

A simple example to go with my post on Compojure. http://vedang.me/techlog/2012/02/23/composability-and-compojure/

  • Download Gist
routes.clj
Clojure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
(ns cello-world.routes
(:require [compojure.route :as route]
[compojure.core :as cc]
[ring.util.response :as rur])
(:use [ring.adapter.jetty :only [run-jetty]]))
 
 
(cc/defroutes hello-routes
(cc/GET "/hello/name/" []
(fn [req]
(rur/response "<h1>Cello Vedang</h1>")))
(cc/GET "/hello/city/" []
(fn [req]
(rur/response "<h1>Cello from Pune!</h1>"))))
 
 
(cc/defroutes main-routes*
(cc/GET "/" [] (fn [req]
(rur/response "<h1>Cello World</h1>")))
(cc/GET "/bye/" [] (fn [req]
(rur/response "<h1>Goodbye World</h1>")))
(cc/GET "/hello*" [] hello-routes)
(route/not-found "<h1>Page not found</h1>"))
 
 
(defn verify-secret
"Verify that secret-key has been sent as a parameter s in the request"
[handler]
(fn [request]
(if (= "s=please" (:query-string request))
(handler request)
{:status 403
:body "You don't know the secret word"})))
 
 
;;; Wrap my main routes in swathes of middleware
(def main-routes (-> #'main-routes*
verify-secret))
 
 
(defonce ^:dynamic *server* nil)
 
 
(defn start-server
[port]
(let [server (run-jetty #'main-routes
{:port port
:join? false})]
(println "Started server on port -" port)
(alter-var-root #'*server* (constantly server))))
 
 
(defn stop-server
[]
(.stop *server*))
 
 
(defn restart
[port]
(when (bound? #'*server*)
(stop-server))
(start-server port))
 
 
(comment
;; to run the program
(start-server 5000)
;; The site should be accessible at 0.0.0.0:5002/
;; An example URL would be 0.0.0.0:5002/?s=please
;; to Stop the server
(stop-server))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.