|
| 1 | +==== Handling form data with Ring |
| 2 | + |
| 3 | +===== Problem |
| 4 | + |
| 5 | +You want your app to accept user input |
| 6 | + |
| 7 | +===== Solution |
| 8 | + |
| 9 | +Use `ring.middleware.params.wrap-params` to add parameters to incoming request maps. |
| 10 | + |
| 11 | +[source, clojure] |
| 12 | +---- |
| 13 | +(ns ringtest |
| 14 | + (:require |
| 15 | + [ring.adapter.jetty :as jetty] |
| 16 | + [ring.middleware.params :refer [wrap-params]])) |
| 17 | +
|
| 18 | +(def GREETING_FORM |
| 19 | + (str |
| 20 | + "<html>" |
| 21 | + " <form action='' method='post'>" |
| 22 | + " Enter your name: <input type='text' name='name'><br/>" |
| 23 | + " <input type='submit' value='Say Hello'>" |
| 24 | + " </form>" |
| 25 | + "</html>")) |
| 26 | +
|
| 27 | +(defn show-form [] |
| 28 | + {:body GREETING_FORM |
| 29 | + :status 200 }) |
| 30 | +
|
| 31 | +(defn show-name |
| 32 | + "A response showing that we know the user's name" |
| 33 | + [name] |
| 34 | + {:body (str "Hello, " name) |
| 35 | + :status 200}) |
| 36 | +
|
| 37 | +(defn handler |
| 38 | + "Show a form requesting the user's name, or greet them if they submitted the form" |
| 39 | + [{params :form-params :as req}] |
| 40 | + (let [name (params "name")] |
| 41 | + (if name |
| 42 | + (show-name name) |
| 43 | + (show-form)))) |
| 44 | +
|
| 45 | +(defn -main [] |
| 46 | + ;; Run the server on port 3000 |
| 47 | + (jetty/run-jetty (wrap-params handler) {:port 3000})) |
| 48 | +---- |
| 49 | + |
| 50 | +===== Discussion |
| 51 | + |
| 52 | +`wrap-params` is a Ring middleware that handles the retrieval of querystring |
| 53 | +and form parameters from raw requests. It adds three keys to the request: |
| 54 | + |
| 55 | +* `:query-params`, containing a map of the parsed querystring parameters, |
| 56 | +* `:form-params`, containing a map of form body parameters, and |
| 57 | +* `:params`, which has the contents of both merged together. |
| 58 | + |
| 59 | +In the above example we use `:form-params`, and so our handler will only |
| 60 | +respond with a greeting on POST requests. If we had used `:params`, we would |
| 61 | +have the option of also passing a query string with a `"name"` parameter. |
| 62 | + |
| 63 | +Note the use of destructuring to retrieve the `:form-params` value from the |
| 64 | +request. This is a pretty common pattern. One gotcha to remember is that the |
| 65 | +params maps have *strings* for keys, not keywords. |
| 66 | + |
0 commit comments