Base64 Encoding in Julia

Here’s the translation of the Base64 Encoding example from Go to Julia:

Julia provides built-in support for base64 encoding/decoding.

using Base64

function main()
    # Here's the string we'll encode/decode.
    data = "abc123!?\$*&()'-=@~"

    # Julia supports both standard and URL-compatible
    # base64. Here's how to encode using the standard
    # encoder.
    sEnc = base64encode(data)
    println(sEnc)

    # Decoding may return an error, which you can check
    # if you don't already know the input to be
    # well-formed.
    sDec = String(base64decode(sEnc))
    println(sDec)
    println()

    # This encodes/decodes using a URL-compatible base64
    # format.
    uEnc = base64encode(data; pad=false)
    println(uEnc)
    uDec = String(base64decode(uEnc))
    println(uDec)
end

main()

The string encodes to slightly different values with the standard and URL base64 encoders (trailing = vs no padding) but they both decode to the original string as desired.

$ julia base64_encoding.jl
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

In Julia, we use the Base64 module for base64 encoding and decoding. The base64encode function is used for encoding, while base64decode is used for decoding.

For URL-compatible encoding, we use the pad=false option with base64encode. This removes the padding characters (=) from the end of the encoded string, making it safe for use in URLs.

Note that in Julia, we don’t need to explicitly convert strings to byte arrays before encoding, as the functions automatically handle this conversion. When decoding, we convert the result back to a string using the String constructor.