Skip to content

Instantly share code, notes, and snippets.

@nunb
Created September 24, 2010 13:52
Show Gist options
  • Select an option

  • Save nunb/595403 to your computer and use it in GitHub Desktop.

Select an option

Save nunb/595403 to your computer and use it in GitHub Desktop.
;; For http://groups.google.com/group/compojure/browse_thread/thread/4abbb541cc3a4c4c
(defn strip-uri-context [context uri]
"Strip context from beginning of uri"
(apply str (drop (count context) uri)))
(defmacro route-context [context route-handler]
"Call a defroute in some context"
`(fn [request#]
(let [uri# (request# :uri)
regex# (re-pattern (str "^" ~context ".*$"))]
(when (re-matches regex# uri#)
(let [stripped# (strip-uri-context ~context uri#)
new-req# (assoc request# :uri stripped#)]
(~route-handler new-req#))))))
;; Example of use:
(cc/defroutes user-routes
(cc/GET "/" []
..)
(cc/POST "/" [user uid full-name topics]
..)
(cc/GET "/:uid/" [uid]
..)
(cc/PUT "/:uid/" [user uid full-name topics]
..)
(cc/GET "/:uid/followers/" [uid]
..))
(cc/defroutes toplevel
(route-context "/users" user-routes) ;; USERS
(route-context "/posts" topic-routes) ;; POSTS
(cc/ANY "*" [] h/echo-handler)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment