Go Example: Base64 Encoding

1. Introduction

Base64 encoding is a method of converting binary data into an ASCII string format by converting it into a radix-64 representation. It is commonly used when there is a need to encode binary data, especially when that data needs to be stored and transferred over media that are designed to deal with textual data. This blog will demonstrate how to perform Base64 encoding in Go.

Definition

Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format by translating it into a radix-64 representation. In Go, the encoding/base64 package provides built-in support for base64 encoding and decoding.

2. Program Steps

1. Import the encoding/base64 package.

2. Define a string to encode.

3. Encode the string into Base64 using base64.StdEncoding.EncodeToString.

4. Decode the Base64 string back to its original format.

5. Handle any errors that might occur during decoding.

3. Code Program

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	// Step 2: Define a string to encode
	data := "Hello, World!"

	// Step 3: Encode the string into Base64
	sEnc := base64.StdEncoding.EncodeToString([]byte(data))
	fmt.Println("Encoded:", sEnc)

	// Step 4: Decode the Base64 string
	sDec, err := base64.StdEncoding.DecodeString(sEnc)
	if err != nil {
		// Step 5: Handle errors
		fmt.Println("Error decoding string:", err)
		return
	}
	fmt.Println("Decoded:", string(sDec))
}

Output:

Encoded: SGVsbG8sIFdvcmxkIQ==
Decoded: Hello, World!

Explanation:

1. The encoding/base64 package is imported, which contains the necessary functions for base64 encoding and decoding.

2. A sample data string "Hello, World!" is defined.

3. base64.StdEncoding.EncodeToString is used to encode the string into base64. It first converts the string into a byte slice since base64 operates on binary data.

4. base64.StdEncoding.DecodeString attempts to decode the base64 encoded string back into the original string. It returns a byte slice and an error.

5. If an error occurs during decoding, it is printed and the program exits.

6. Otherwise, the decoded data is converted from a byte slice back to a string and printed.

7. The output verifies that the original data is correctly encoded to base64 and then decoded back to its original form.


Comments