Development

How to Decode and Encode Base64 in Go

A practical guide to the encoding/base64 package in Go. Learn how to encode to strings, decode to byte slices, and handle custom encodings.

Published on August 18, 20265 min read

The Go standard library provides the encoding/base64 package for all Base64 operations. In Go, you work directly with predefined encoding objects like StdEncoding or URLEncoding.

Byte Slices vs Strings

In Go, standard Base64 functions take a byte slice ([]byte) as input, not a string. You will constantly cast between strings and byte slices using []byte("string") and string(bytes).

1. Encode a String to Base64 in Go

Use base64.StdEncoding.EncodeToString() to convert a byte slice into a Base64 string.

go
package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	text := "Hello, Go Base64!"
	
	// Convert string to byte slice and encode
	encoded := base64.StdEncoding.EncodeToString([]byte(text))
	
	fmt.Println("Encoded:", encoded)
	// Output: Encoded: SGVsbG8sIEdvIEJhc2U2NCE=
}

2. Decode a Base64 String in Go

Use base64.StdEncoding.DecodeString() to reverse the process. This function returns two values: the decoded byte slice and an error. You must explicitly check the error.

go
package main

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

func main() {
	encoded := "SGVsbG8sIEdvIEJhc2U2NCE="
	
	// DecodeString returns []byte and an error
	decodedBytes, err := base64.StdEncoding.DecodeString(encoded)
	if err != nil {
		log.Fatalf("Failed to decode: %v", err)
	}
	
	// Cast the byte slice back to a string
	fmt.Println("Decoded:", string(decodedBytes))
	// Output: Decoded: Hello, Go Base64!
}

3. URL-Safe Base64 in Go

For URL-safe encoding (replacing + with - and / with _), Go provides the URLEncoding object. If you need to omit the padding (=) entirely, use RawURLEncoding.

go
package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	data := []byte("subjects?dir=/usr/local")
	
	// Standard URLEncoding (includes padding '=')
	urlSafe := base64.URLEncoding.EncodeToString(data)
	fmt.Println("URL Safe:    ", urlSafe)
	// Output: c3ViamVjdHM_ZGlyPS91c3IvbG9jYWw=
	
	// RawURLEncoding (omits padding '=') - highly recommended for JWTs
	rawUrlSafe := base64.RawURLEncoding.EncodeToString(data)
	fmt.Println("Raw URL Safe:", rawUrlSafe)
	// Output: c3ViamVjdHM_ZGlyPS91c3IvbG9jYWw
}

Debugging Base64 from Go?

If your Go application outputs a Base64 string that isn't decoding as expected, use our interactive toolkit to inspect the raw characters.

Go to the Base64 Converter Tool