The encoding/base64
package contains several built in encoders. Most of the examples in this document will use base64.StdEncoding
, but any encoder (URLEncoding
, RawStdEncodign
, your own custom encoder, etc.) may be substituted.
const foobar = `foo bar`
encoding := base64.StdEncoding
encodedFooBar := make([]byte, encoding.EncodedLen(len(foobar)))
encoding.Encode(encodedFooBar, []byte(foobar))
fmt.Printf("%s", encodedFooBar)
// Output: Zm9vIGJhcg==
str := base64.StdEncoding.EncodeToString([]byte(`foo bar`))
fmt.Println(str)
// Output: Zm9vIGJhcg==
encoding := base64.StdEncoding
data := []byte(`Zm9vIGJhcg==`)
decoded := make([]byte, encoding.DecodedLen(len(data)))
n, err := encoding.Decode(decoded, data)
if err != nil {
log.Fatal(err)
}
// Because we don't know the length of the data that is encoded
// (only the max length), we need to trim the buffer to whatever
// the actual length of the decoded data was.
decoded = decoded[:n]
fmt.Printf("`%s`", decoded)
// Output: `foo bar`
decoded, err := base64.StdEncoding.DecodeString(`biws`)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", decoded)
// Output: n,,