Base64 Encoding in Golang

Golang provides built-in support for Base64 encoding and decoding. In this article, you’ll find examples demonstrating how to perform Base64 encoding in Golang.

Go’s encoding/base64 package implements base64 encoding as specified by RFC 4648. It provides implementations for both Standard as well as URL and Filename safe Base64 encoding variant.

Golang Base64 Encoding

As defined in the RFC 4648, the standard Base64 encoding encodes any binary data to a subset of the US-ASCII character set containing the characters: A-Z, a-z, 0-9, +, and /:

package main

import (
	"encoding/base64"
	"fmt"
)

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

	// Base64 Standard Encoding
	sEnc := base64.StdEncoding.EncodeToString([]byte(data))
	fmt.Println(sEnc)
}
$ go run base64_encode.go
aGVsbG8gd29ybGQxMjM0NSE/JComKCknLUB+

Golang Base64 URL and Filename safe Encoding

Base64 URL encoding is a variant of Base64 encoding whose output is safe to be placed in URLs and Filenames. Since + and / characters which are part of the standard Base64 alphabet are not URL and Filename safe, this variant replaces + with minus (-) and / with underscore (_):

package main

import (
	"encoding/base64"
	"fmt"
)

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

	// Base64 Url Encoding
	uEnc := base64.URLEncoding.EncodeToString([]byte(data))
	fmt.Println(uEnc)
}
$ go run base64_encode.go
aGVsbG8gd29ybGQxMjM0NSE_JComKCknLUB-

Golang Base64 Encoding without Padding

The standard Base64 encoding pads the Base64 encoded output with = character. It is recommended to use padding character. However, in some circumstances, the use of padding in base-64 encoded data is not required. To Base64 encode without padding, you can use the Raw encodings provided by Golang -

package main

import (
	"encoding/base64"
	"fmt"
)

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

	// Base64 Encoding without Padding
	swEnc := base64.RawStdEncoding.EncodeToString([]byte(data))
	fmt.Println(swEnc)

	// Base64 Url Encoding without Padding
	uwEnc := base64.RawURLEncoding.EncodeToString([]byte(data))
	fmt.Println(uwEnc)
}
$ go run base64_encode.go
YWJjIT8kKiYoKSctQH4
YWJjIT8kKiYoKSctQH4

Also Read: Golang Base64 Decode Example

References