To encode and decode base64 data using the bytes
package in Go, you can follow the steps below:
import (
"encoding/base64"
"fmt"
"bytes"
)
data := []byte("Hello, World!") // Convert string to byte slice
encodedData := make([]byte, base64.StdEncoding.EncodedLen(len(data)))
// Encode the data and store the result in the encodedData slice
base64.StdEncoding.Encode(encodedData, data)
fmt.Println(string(encodedData))
decodedData := make([]byte, base64.StdEncoding.DecodedLen(len(encodedData)))
// Decode the encoded data and store the result in the decodedData slice
_, err := base64.StdEncoding.Decode(decodedData, encodedData)
if err != nil {
fmt.Println("Error decoding base64:", err)
return
}
fmt.Println(string(decodedData))
The encoded data will be printed as "SGVsbG8sIFdvcmxkIQ==" and the decoded data will be printed as "Hello, World!"