Golang base64 Encode Example
Golang provides built in support for base64 encoding/decoding. Directly in the standard library we have "encoding/base64" so there is no need to download or install third-party libraries. Let’s have a look at the Go base64 encoding documentation https://golang.org/pkg/encoding/base64/. In order to encode or decode a string to and from base64 we need to use the type Encoder which provides the following methods
func (enc *Encoding) DecodeString(s string) ([]byte, error)
and to encode a string (in this case a slice of bytes) to base64 format
func (enc *Encoding) EncodeToString(src []byte) string
the standard library also provides us methods that decode and encode from and to byte slices for more general purpose usages (Decode, Encode).
Here is an example on how to encode and decode base64 strings
package main
import (
"encoding/base64"
"fmt"
)
func main() {
// Here's the `string` we'll encode
plainStr := "Hello World."
// The encoder we will use is the base64.StdEncoding
// It requires a byte slice so we cast the string to []byte
encodedStr := base64.StdEncoding.EncodeToString([]byte(plainStr))
fmt.Println(encodedStr)
// Decoding may return an error, in case the input is not well formed
decodedStrAsByteSlice, err := base64.StdEncoding.DecodeString(encodedStr)
if err != nil {
panic("malformed input")
}
fmt.Println(string(decodedStrAsByteSlice))
}
Here is the expected output
SGVsbG8gV29ybGQu
Hello World.