Skip to content

Commit ca2002c

Browse files
committed
Add form-decode-map function
1 parent ab9c557 commit ca2002c

File tree

2 files changed

+43
-10
lines changed

2 files changed

+43
-10
lines changed

src/ring/util/codec.clj

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,24 @@
166166
(zero? i) (MapEntry. "" (.substring s (inc i)))
167167
:else (MapEntry. s ""))))
168168

169+
(defn form-decode-map
170+
"Decode the supplied www-form-urlencoded string using the specified encoding,
171+
or UTF-8 by default. Expects an encoded map of key/value pairs as defined by:
172+
https://url.spec.whatwg.org/#urlencoded-parsing"
173+
([encoded]
174+
(form-decode-map encoded utf-8))
175+
([^String encoded encoding]
176+
(reduce
177+
(fn [m param]
178+
(let [kv (split-key-value-pair param)
179+
k (form-decode-str (key kv) encoding)
180+
v (form-decode-str (val kv) encoding)]
181+
(if (and k v)
182+
(assoc-conj m k v)
183+
m)))
184+
{}
185+
(tokenized encoded "&"))))
186+
169187
(defn form-decode
170188
"Decode the supplied www-form-urlencoded string using the specified encoding,
171189
or UTF-8 by default. If the encoded value is a string, a string is returned.
@@ -175,13 +193,4 @@
175193
([^String encoded encoding]
176194
(if-not (.contains encoded "=")
177195
(form-decode-str encoded encoding)
178-
(reduce
179-
(fn [m param]
180-
(let [kv (split-key-value-pair param)
181-
k (form-decode-str (key kv) encoding)
182-
v (form-decode-str (val kv) encoding)]
183-
(if (and k v)
184-
(assoc-conj m k v)
185-
m)))
186-
{}
187-
(tokenized encoded "&")))))
196+
(form-decode-map encoded encoding))))

test/ring/util/test/codec.clj

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,30 @@
6161
(is (= (form-decode-str "foo=bar+baz" nil) "foo=bar baz"))
6262
(is (= (form-decode-str "foo=bar+baz" "UTF-8") "foo=bar baz")))
6363

64+
(deftest test-form-decode-map
65+
(are [x y] (= (form-decode-map x) y)
66+
"foo" {"foo" ""}
67+
"a=b" {"a" "b"}
68+
"a=b&c=d" {"a" "b" "c" "d"}
69+
"foo+bar" {"foo bar" ""}
70+
"a=b+c" {"a" "b c"}
71+
"a=b%2Fc" {"a" "b/c"}
72+
"a=b&c" {"a" "b" "c" ""}
73+
"a=&b=c" {"a" "" "b" "c"}
74+
"a&b=c" {"a" "" "b" "c"}
75+
"=" {"" ""}
76+
"a=" {"a" ""}
77+
"=b" {"" "b"})
78+
(testing "invalid URL encoding"
79+
(are [x y] (= (form-decode-map x) y)
80+
"%=b" {}
81+
"a=%" {}
82+
"%=%" {}))
83+
(is (= (form-decode-map "a=foo%FE%FF%00%2Fbar" "UTF-16")
84+
{"a" "foo/bar"}))
85+
(is (= (form-decode-map "a=foo%2Fbar" nil)
86+
{"a" "foo/bar"})))
87+
6488
(deftest test-form-decode
6589
(are [x y] (= (form-decode x) y)
6690
"foo" "foo"

0 commit comments

Comments
 (0)