Compojure: how to map query parameters

pistacchio picture pistacchio · Oct 16, 2011 · Viewed 9.9k times · Source

I'm trying to make any of the following mappings work to map http://mysite.org/add?http://sitetoadd.com or http://mysite.org/add?u=http://sitetoadd.com

  (GET "/add?:url" [url] url)
  (GET "/add?u=:url" [url] url)
  (GET "/add" {params :params} (params :u))
  (GET "/add" {params :params} (params "u"))
  (GET "/add" [u] u)

But it just fails and I don't know why. On the other hand, this works:

  (GET "/add/:url" [url] url)

but I can't use it because I have to pass a url and http://mysite.org/add/http://sitetoadd.com is invalid while http://mysite.org/add?http://sitetoadd.com is ok.

EDIT: dumping request i've seen that params is empty. I thought that it would contain POST and GET parameters, but the only place where I can find the params I pass is in :query-string ("u=asd"). It seems that a middleware is needed to parse query strings. My question stands still, by the way.

Answer

Marius Kjeldahl picture Marius Kjeldahl · Oct 16, 2011

See https://github.com/weavejester/compojure under Breaking Changes. The params map is no longer bound by default. If you have your example routes inside a "(defroutes main-routes ... )", make sure you activate it through "(handler/site main-routes)" as explained on https://github.com/weavejester/compojure/wiki/Getting-Started as it is the site or api method that makes sure the params map gets bound by default.

Here's an example that works:

(ns hello-world
  (:use compojure.core, ring.adapter.jetty)
  (:require [compojure.route :as route]
            [compojure.handler :as handler]))

(defroutes main-routes
  (GET "/" {params :params} (str "<h1>Hello World</h1>" (pr-str params)))
  (route/not-found "<h1>Page not found</h1>"))

(defn -main [& m]
  (run-jetty (handler/site main-routes) {:port 8080}))