Sling Academy
Home/Golang/Encoding and Decoding Strings in Base64 in Go

Encoding and Decoding Strings in Base64 in Go

Last updated: November 24, 2024

Base64 encoding is used to convert binary data into an ASCII string format by translating it into a radix-64 representation. This is often used in data encoding on the internet where the data might need to be saved and transferred in textual format. In Go, the encoding/base64 package provides built-in functions for encoding and decoding strings into/from Base64.

Basic Level

Encoding a String to Base64

Let's start by encoding a simple string into Base64. In Go, you can use the StdEncoding.EncodeToString method provided by the encoding/base64 package.


package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	data := "Hello, World!"
	encoded := base64.StdEncoding.EncodeToString([]byte(data))
	fmt.Println("Encoded:", encoded)
}

When you run the above code, it will output:


Encoded: SGVsbG8sIFdvcmxkIQ==

Decoding a Base64 String

Decoding follows a similar process using the StdEncoding.DecodeString method. Here’s how you can decode a previously encoded string:


package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	encoded := "SGVsbG8sIFdvcmxkIQ=="
	decoded, err := base64.StdEncoding.DecodeString(encoded)
	if err != nil {
		fmt.Println("Error decoding string:", err)
		return
	}
	fmt.Println("Decoded:", string(decoded))
}

The output from the above code is:


Decoded: Hello, World!

Intermediate Level

Handling Binary Data

Base64 encoding is not limited to strings only; it can be used to encode and decode binary data as well. Here's an example using binary data:


package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	binaryData := []byte{0xff, 0xe4, 0x123, 0xff}
	encoded := base64.StdEncoding.EncodeToString(binaryData)
	fmt.Println("Encoded Binary:", encoded)

	decoded, err := base64.StdEncoding.DecodeString(encoded)
	if err != nil {
		fmt.Println("Error decoding binary:", err)
	}
	fmt.Println("Decoded Binary:", decoded)
}

URL Encoding

If you are encoding data that will be part of a URL, you should use the URL-safe base64 encoding. Go provides the URLEncoding variant for such purposes.


package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	data := "Hello, URL World!"
	encoded := base64.URLEncoding.EncodeToString([]byte(data))
	fmt.Println("URL Encoded:", encoded)

	decoded, err := base64.URLEncoding.DecodeString(encoded)
	if err != nil {
		fmt.Println("Error decoding URL string:", err)
		return
	}
	fmt.Println("URL Decoded:", string(decoded))
}

Advanced Level

Custom Base64 Encoding

You might encounter scenarios where you need to encode data in a Base64 format that’s not standard. Go allows the creation of a custom Base64 encoding.

Here's how you create a custom encoder. We'll use an example where we change the characters used in encoding:


package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	customEncoding := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").WithPadding(base64.NoPadding)
	data := "Custom Base64"
	encoded := customEncoding.EncodeToString([]byte(data))
	fmt.Println("Custom Encoded:", encoded)

	decoded, err := customEncoding.DecodeString(encoded)
	if err != nil {
		fmt.Println("Error decoding custom string:", err)
	}
	fmt.Println("Custom Decoded:", string(decoded))
}

In this example, we use the standard Base64 table but remove padding by using the WithPadding method. You can modify each character to suit any necessary custom encoding.

By understanding these concepts and examples, you can effectively manage Base64 encoding and decoding in your Go applications, whether it involves simple strings or more complex data forms.

Next Article: Working with Whitespace in Go Strings

Previous Article: Regular Expressions for String Matching in Go

Series: Working with Strings in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant