Base64 Decoding in Golang

In this article, you’ll learn how to Base64 decode any Base64 encoded data back to binary data. 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

The following example shows how to decode a Base64 encoded data back to a sequence of bytes. It uses the Standard Base64 encoding -

package main

import (
	"encoding/base64"
	"fmt"
)

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

	sEnc := base64.StdEncoding.EncodeToString([]byte(data))

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

	fmt.Println(string(sDec))
}
# Output
$ go run base64_decode.go
hello world12345!?$*&()'-@~

Golang Base64 URL Decoding Example

The following example decodes the Base64 encoded data using the URL and Filename safe variant of Base64 encoding -

package main

import (
	"encoding/base64"
	"fmt"
)

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

	uEnc := base64.URLEncoding.EncodeToString([]byte(data))

    // Base64 Url Decoding
	uDec, err := base64.URLEncoding.DecodeString(uEnc)
	if err != nil {
		fmt.Printf("Error decoding string: %s ", err.Error())
		return
	}
	
	fmt.Println(string(uDec))
}
# Output
$ go run base64_decode.go
hello world12345!?$*&()'-@~

Also Read: Golang Base64 Encode Example

Reference