« back

Base64 Encoding with Clojure

06 Dec 2012

Today let's take a look at base64 encoding with clojure.

After finishing up a command parser, as a bonus challenge, I was going to add base64 encoding. Of course, my first thought was 'Has someone written that for clojure?'. It turns out that they had.... BUT in the wake of the clojure contrib breakup, as things were ported over to new namespaces, some of the original functions of the namespaces were not migrated. So, the wonderful (encode-str), which was exactly what I needed, was no longer. I thought that the (encode) function might work but that only gave me back a base64 encoded byte array and I needed a string. Here is what I ended up with...

1 (defn base-64 [message]
2 	 (String. (b64/encode (.getBytes message))))

I did something similar for decoding as well..

1 (defn decode-base-64 [message]
2 	 (String. (b64/decode (.getBytes message))))

This meant that I would need to modify my functions that created and decoded structured messages. What I did was add a parameter to the function that would take a kind of encoding. Something like this...

1 (defn create-structured-message [command-id message encoding])

What's great about this is that I can pass different types of encoding if I decided to make them available in the future. I did make a function that would just return a message if you passed no-encoding.

1 (defn no-encoding [message]
2 	message)

Then, I set default values for creating and decoding structured messages.

1 (defn decode-structured-messages
2 	([input] (decode-structured-message input plain-text))
3 	([input decoder]
1 (defn create-structured-message
2 	([command-id message] (create-structured-message command-id message no-encoding))
3 	([command-id message encoding]

Now I know I didn't quite give you a step by step this time but I think if you look here and here, you'll be able to piece it together. ;)

comments powered by Disqus