Last active
August 29, 2015 13:56
-
-
Save ptn/9007407 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns router.core | |
(:gen-class) | |
(:use [clojure.string | |
:only [replace] | |
:rename {replace str-replace}])) | |
(defn- build-route [[url-spec handler]] | |
(let [regex (re-pattern (str-replace url-spec #":.+?\/" "(.+?)/"))] | |
`(fn [url#] | |
(if-let [match# (re-matches ~regex url#)] | |
(if (coll? match#) | |
(fn [] (apply ~handler (drop 1 match#))) | |
(fn [] (~handler))))))) | |
(defn not-found [] (println "404 Not Found")) | |
(defmacro defroutes [& route-forms] | |
(let [handlers (map build-route (partition 2 route-forms))] | |
`(def routes [~@handlers (fn [url#] (fn [] (not-found)))]))) | |
(defroutes | |
"/router/both/" (fn [] (println "router both")) | |
"/only/controller/" (fn [] (println "only controller")) | |
"/router/params/:x/:y/:z/" (fn [x y z] (println x y z))) | |
(defmacro with-handler [[var url] & body] | |
`(let [url# ~url | |
handler# (some #(% url#) routes) | |
~var handler#] | |
(do ~@body))) | |
(defn route [url] | |
(with-handler [handler url] | |
(handler))) | |
(defn -main [& args] | |
(route "/router/both/") | |
(route "/only/controller/") | |
(route "/router/params/1/2/3/") | |
(route "NOPE")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
:10s/if-let/when-let/g