Base64 Encoding in Elixir
Here’s the translation of the Base64 Encoding example from Go to Elixir, formatted in Markdown suitable for Hugo:
Elixir provides built-in support for base64 encoding/decoding.
In Elixir, we use the Base
module for base64 encoding and decoding. This module is part of Elixir’s standard library, so we don’t need to import it explicitly.
We define a module Base64Example
with a run
function that demonstrates the encoding and decoding process.
The Base.encode64/1
function is used for standard base64 encoding. It takes a binary (which in Elixir, strings are stored as binaries) and returns the encoded string.
For decoding, we use Base.decode64/1
. This function returns a tuple {:ok, decoded_string}
if the decoding is successful, or {:error, :invalid_base64}
if it fails. We use pattern matching to handle the successful case.
Elixir also provides URL-safe base64 encoding and decoding with Base.url_encode64/1
and Base.url_decode64/1
respectively.
When you run this program, you’ll see output similar to this:
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.
In Elixir, error handling is typically done through pattern matching and the use of {:ok, result}
and {:error, reason}
tuples. This is different from many other languages that use exception handling for such cases.