To encode a string to Base64 in Go, use the EncodeToString()
function from the encoding/base64
standard library package. This function takes a byte slice and converts it to a Base64 encoded string, but it can also be used for a string argument by converting it to a byte slice.
Check also how to decode Base64 to a string in Go.
package main
import (
"encoding/base64"
"fmt"
)
func main() {
text := "hello from gosamples.dev base64 encoding example!"
encodedText := base64.StdEncoding.EncodeToString([]byte(text))
fmt.Printf("Encoded text: %s\n", encodedText)
}
Output:
Encoded text: aGVsbG8gZnJvbSBnb3NhbXBsZXMuZGV2IGJhc2U2NCBlbmNvZGluZyBleGFtcGxlIQ==
The EncodeToString()
is a method of StdEncoding
which is an object representing the standard base64 encoding, as defined in RFC 4648.