Base64 Encoding in Haskell
Here’s the translation of the Base64 Encoding example from Go to Haskell, formatted in Markdown suitable for Hugo:
Haskell provides support for base64 encoding/decoding through the base64-bytestring
package. This example demonstrates how to use it.
First, we import the necessary modules: Data.ByteString.Base64
for base64 operations and Data.ByteString.Char8
for working with ByteStrings.
In the main
function, we define our sample string data
.
For standard base64 encoding:
- We use
B64.encode
to encode the ByteString version of our data. - We print the encoded string after converting it back to a regular String.
For decoding:
- We use
B64.decode
which returns anEither
type. - We handle both success and error cases using pattern matching.
The process is similar for URL-safe base64 encoding/decoding, but we use B64.encodeUrlSafe
and B64.decodeUrlSafe
instead.
Note that in Haskell, we’re working with ByteStrings instead of the []byte
type used in the original example. This is idiomatic for Haskell when dealing with binary data or text that needs to be processed efficiently.
To run this program:
The string encodes to slightly different values with the standard and URL base64 encoders (trailing +
vs -
) but they both decode to the original string as desired.