Permalink
Browse files

Introduce ring.util.codec/url-encode and add tests for the rest of th…

…e namespace.
  • Loading branch information...
1 parent a977eba commit 820e6dd3ab0c71bcb90726079408da6c6e1bc912 @mmcgrana committed Mar 3, 2010
Showing with 23 additions and 1 deletion.
  1. +7 −1 ring-core/src/ring/util/codec.clj
  2. +16 −0 ring-core/test/ring/util/codec_test.clj
View
8 ring-core/src/ring/util/codec.clj
@@ -1,9 +1,15 @@
(ns ring.util.codec
"Encoding and decoding utilities."
(:import java.io.File
- java.net.URLDecoder
+ (java.net URLEncoder URLDecoder)
org.apache.commons.codec.binary.Base64))
+(defn url-encode
+ "Returns the form-url-encoded ersion of the given string, using either a
+ specified encoding or UTF-8 by default."
+ [unencoded & [encoding]]
+ (URLEncoder/encode unencoded (or encoding "UTF-8")))
+
(defn url-decode
"Returns the form-url-decoded version of the given string, using either a
specified encoding or UTF-8 by default."
View
16 ring-core/test/ring/util/codec_test.clj
@@ -0,0 +1,16 @@
+(ns ring.util.codec-test
+ (:use clojure.test
+ ring.util.codec)
+ (:import java.util.Arrays))
+
+(deftest test-url-encode
+ (is (= "foo%2Fbar" (url-encode "foo/bar")))
+ (is (= "foo%FE%FF%00%2Fbar") (url-encode "foo/bar" "UTF-16")))
+
+(deftest test-url-decode
+ (is (= "foo/bar" (url-decode "foo%2Fbar")))
+ (is (= "foo/bar" (url-decode "foo%FE%FF%00%2Fbar" "UTF-16"))))
+
+(deftest test-base64-encoding
+ (let [str-bytes (.getBytes "foo?/+" "UTF-8")]
+ (is (Arrays/equals str-bytes (base64-decode (base64-encode str-bytes))))))

0 comments on commit 820e6dd

Please sign in to comment.