Search code examples
clojurecompojure

error while composing routes in compojure


The following compojure routes work.

(defroutes app-routes
  (GET "/" [] (index))
  (GET "/twauth" [] (tw/authorize))
  (ANY "/twcallback" [] (do
                          (tw/callback)
                          (index)))
  (route/resources "/")
  (route/not-found "Not Found"))

(def app (handler/site app-routes))

However I get error with the following. It throws a java.nullpointer.exception. What am I doing wrong here ?

(defroutes app-routes (GET "/" [] (index)) (GET "/twauth" [] (tw/authorize)) (ANY "/twcallback" [] (do (tw/callback) (index))))

(defroutes base-routes
  (route/resources "/")
  (route/not-found "Not Found"))

(def app
  (-> app-routes
      base-routes
      handler/site))

Solution

  • Your base-routes matches all requests. I think the following illustrates it better:

    (defroutes base-routes
      (route/not-found "Not found"))
    
    (def app
      (-> app-routes
          base-routes
          handler/site))
    

    No matter what you do in app-routes above, base-routes is checked after and will always return not-found. Note that each request is threaded through both routes, not first match wins.

    So you need to either move the base-routes into your app-routes as fallbacks -- like you already did in your working example -- or compose them in app:

    (def app
      (-> (routes app-routes base-routes)
          handler/site))
    

    Here the composed routes ensures that the first match wins.