Go by Example: Base64 Encoding

Go provides a encoding/base64 package that implements base64 encoding and decoding. Here’s an example of how you can use the base64 package to encode and decode data:

package main

import (

func main() {
	// Encode a string to base64
	data := "hello, world"
	encoded := base64.StdEncoding.EncodeToString([]byte(data))
	fmt.Println("Encoded:", encoded)

	// Decode a base64 string
	decoded, err := base64.StdEncoding.DecodeString(encoded)
	if err != nil {
		fmt.Println("Decode error:", err)
	fmt.Println("Decoded:", string(decoded))

In this example, the base64.StdEncoding.EncodeToString function is used to encode a string to base64. The input to this function is a byte slice, so we first convert the string to a byte slice using the []byte conversion.

The base64.StdEncoding.DecodeString function is used to decode a base64 string. The result of this function is a byte slice, which we then convert to a string using the string conversion.

The output of this program will be:

Encoded: aGVsbG8sIHdvcmxk
Decoded: hello, world


Leave a Reply

Your email address will not be published. Required fields are marked *