Implementing Base64 in Golang
Golang provides built-in support for Base64 encoding and decoding through the encoding/base64
package. This package offers a simple and efficient way to work with Base64 data in your Golang applications.
Here's an example of how to use the encoding/base64
package to encode and decode data:
package main
import (
"encoding/base64"
"fmt"
)
func main() {
// Encode binary data to Base64
binaryData := []byte{0x14, 0x7b, 0x9f, 0x86, 0x5c, 0x7a, 0x03, 0x8d}
encodedData := base64.StdEncoding.EncodeToString(binaryData)
fmt.Println("Encoded data:", encodedData) // Output: Encoded data: FHv58lx6A40=
// Decode Base64 data to binary
decodedData, err := base64.StdEncoding.DecodeString(encodedData)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Decoded data:", decodedData) // Output: Decoded data: [20 123 159 134 92 122 3 141]
}
In this example, we first encode the binary data [0x14, 0x7b, 0x9f, 0x86, 0x5c, 0x7a, 0x03, 0x8d]
to a Base64 string using the base64.StdEncoding.EncodeToString()
function. The resulting Base64 string is "FHv58lx6A40="
.
Next, we decode the Base64 string back to binary data using the base64.StdEncoding.DecodeString()
function. The decoded binary data is [20 123 159 134 92 122 3 141]
, which matches the original binary data.
The encoding/base64
package also provides other encoding options, such as URL-safe Base64 encoding, which is useful when embedding Base64 data in URLs. You can use the base64.URLEncoding
or base64.RawURLEncoding
variants for this purpose.
Furthermore, the package supports streaming encoding and decoding, which can be useful for processing large amounts of data. You can use the base64.Encoder
and base64.Decoder
types for this purpose.
By utilizing the built-in encoding/base64
package, you can easily integrate Base64 encoding and decoding into your Golang applications, making it a powerful tool for working with binary data in a text-based environment.