How to encode and decode base64 data using the bytes package in Go?

To encode and decode base64 data using the bytes package in Go, you can follow the steps below:

  1. Import the required packages:
import ( "encoding/base64" "fmt" "bytes" )
  1. Encode Base64 data:
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))
  1. Decode Base64 data:
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!"