Skip to content

Instantly share code, notes, and snippets.

@vedang
Created February 23, 2012 16:24
Show Gist options
  • Save vedang/1893532 to your computer and use it in GitHub Desktop.
Save vedang/1893532 to your computer and use it in GitHub Desktop.
A simple example to go with my post on Compojure. http://vedang.me/techlog/2012/02/23/composability-and-compojure/
(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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment