To encode and decode data as Base64 in MIME messages in Go, you can use the encoding/base64
package. Here's an example of encoding and decoding data using Base64 in MIME messages:
package main
import (
"encoding/base64"
"fmt"
)
func main() {
// Encode data as Base64
message := "Hello, World!"
encodedMessage := base64.StdEncoding.EncodeToString([]byte(message))
fmt.Println("Encoded message:", encodedMessage)
// Decode Base64 encoded data
decodedMessage, err := base64.StdEncoding.DecodeString(encodedMessage)
if err != nil {
fmt.Println("Decoding error:", err)
return
}
fmt.Println("Decoded message:", string(decodedMessage))
}
Output:
Encoded message: SGVsbG8sIFdvcmxkIQ==
Decoded message: Hello, World!
In this example, we use the EncodeToString
function to encode the message
string to Base64. Then, the DecodeString
function is used to decode the Base64-encoded message. Note that the DecodeString
function returns an error if there's an issue with decoding, so it's a good practice to handle the error appropriately.