Go ships with an encoding/base64 package that allows for encode and decoding of Base64 strings.

Import the base64 package and then start using it!

Base64 encode/decode a string

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
	b64 "encoding/base64"
	"fmt"
)

func main() {
	// define a string
	data := "This is a test string!"

	// Encode to Base64
	sEnc := b64.StdEncoding.EncodeToString([]byte(data))
	fmt.Println(sEnc)

	// Decode from Base64
	sDec, _ := b64.StdEncoding.DecodeString(sEnc)
	fmt.Println(string(sDec))

	// URL Encode
	uEnc := b64.URLEncoding.EncodeToString([]byte(data))
	fmt.Println(uEnc)

	// URL Decode
	uDec, _ := b64.URLEncoding.DecodeString(uEnc)
	fmt.Println(string(uDec))
}