Golang Base64 Decoding Example

In the previous source code example, we have seen Golang Base64 Encoding Example. In this source code example, you’ll learn how to Base64 decode any Base64 encoded data back to binary data.

Golang provides built-in support for Base64 encoding and decoding.

Go’s base64 package contains implementations for both Standard Base64 encoding/decoding as well as URL and Filename safe Base64 encoding/decoding as described in RFC 4648

Golang Base64 Decoding Example

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	data := "hello:world!?$*&()'-=@~"

	// Base64 Standard Decoding
	sEnc := base64.StdEncoding.EncodeToString([]byte(data))
	sDec, err := base64.StdEncoding.DecodeString(sEnc)
	if err != nil {
		fmt.Printf("Error decoding string: %s ", err.Error())
		return
	}
	fmt.Println(string(sDec))

	// Base64 Url Decoding
	uEnc := base64.URLEncoding.EncodeToString([]byte(data))
	uDec, err := base64.URLEncoding.DecodeString(uEnc)
	if err != nil {
		fmt.Printf("Error decoding string: %s ", err.Error())
		return
	}
	fmt.Println(string(uDec))

}
Output:
hello:world!?$*&()'-=@~
hello:world!?$*&()'-=@~
Let's understand the above source code step by step.

Golang Base64 Decoding:

	data := "hello:world!?$*&()'-=@~"

	// Base64 Standard Decoding
	sEnc := base64.StdEncoding.EncodeToString([]byte(data))
	sDec, err := base64.StdEncoding.DecodeString(sEnc)
	if err != nil {
		fmt.Printf("Error decoding string: %s ", err.Error())
		return
	}
	fmt.Println(string(sDec))

Golang Base64 URL Decoding:

	// Base64 Url Decoding
	uEnc := base64.URLEncoding.EncodeToString([]byte(data))
	uDec, err := base64.URLEncoding.DecodeString(uEnc)
	if err != nil {
		fmt.Printf("Error decoding string: %s ", err.Error())
		return
	}
	fmt.Println(string(uDec))

Related Golang Examples


Comments