Golang Base64 Encoding Example

In this source code example, you’ll find examples demonstrating how to perform Base64 encoding in Golang.

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

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 Example

package main

import (
	"encoding/base64"
	"fmt"
)

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

	// Base64 Standard Encoding
	sEnc := base64.StdEncoding.EncodeToString([]byte(data))
	fmt.Println(sEnc)

	// Base64 Url Encoding
	uEnc := base64.URLEncoding.EncodeToString([]byte(data))
	fmt.Println(uEnc)

	// ====================================

	// 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)
}
Output:
aGVsbG8gd29ybGQxMjM0NSE/JComKCknLUB+
aGVsbG8gd29ybGQxMjM0NSE_JComKCknLUB-
aGVsbG8gd29ybGQxMjM0NSE/JComKCknLUB+
aGVsbG8gd29ybGQxMjM0NSE_JComKCknLUB-
Let's understand the above source code step by step.

Golang Base64 Encoding:

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

	// Base64 Standard Encoding
	sEnc := base64.StdEncoding.EncodeToString([]byte(data))
	fmt.Println(sEnc)

Golang Base64 URL and Filename safe Encoding:

	// Base64 Url Encoding
	uEnc := base64.URLEncoding.EncodeToString([]byte(data))
	fmt.Println(uEnc)

Golang Base64 Encoding without Padding

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

Base64 Url Encoding without Padding:

	// Base64 Url Encoding without Padding
	uwEnc := base64.RawURLEncoding.EncodeToString([]byte(data))
	fmt.Println(uwEnc)

Related Golang Examples


Comments