Try it yourself with our free Base64 tool — runs entirely in your browser, no signup needed.

How to Base64 encode in Go

How to Base64 encode in Go

Base64 encoding is a widely used technique to represent binary data as a string of text characters. This is particularly useful when transmitting or storing binary data in environments that only support text, such as email or JSON data. In Go, Base64 encoding is a common operation that can be easily performed using the encoding/base64 package. In this guide, we will walk through the process of Base64 encoding in Go, covering the basics, common use cases, and edge cases.

Quick Example

Here is a minimal example of how to Base64 encode a string in Go:

package main

import (
	"encoding/base64"
	"fmt"
)

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

This code imports the encoding/base64 package and uses the StdEncoding.EncodeToString function to encode the string "Hello, World!" into a Base64-encoded string.

Step-by-Step Breakdown

Let's walk through the code line by line:

  • package main: This is the package declaration, which is required for every Go program.
  • import "encoding/base64": This line imports the encoding/base64 package, which provides the Base64 encoding functions.
  • func main(): This is the main function, which is the entry point of the program.
  • data := "Hello, World!": This line declares a string variable data with the value "Hello, World!".
  • encoded := base64.StdEncoding.EncodeToString([]byte(data)): This line encodes the string data into a Base64-encoded string using the StdEncoding.EncodeToString function. The []byte(data) conversion is necessary because the EncodeToString function expects a byte slice as input.
  • fmt.Println(encoded): This line prints the encoded string to the console.

Handling Edge Cases

Empty/Null Input

When encoding an empty string, the EncodeToString function will return an empty string. This is the expected behavior, as there is no data to encode.

encoded := base64.StdEncoding.EncodeToString([]byte(""))
fmt.Println(encoded) // Output: ""

Invalid Input

If the input is not a valid string (e.g., a nil pointer), the EncodeToString function will panic. To handle this case, you can add error checking before calling the function.

data := (*string)(nil)
if data != nil {
	encoded := base64.StdEncoding.EncodeToString([]byte(*data))
	fmt.Println(encoded)
} else {
	fmt.Println("Error: invalid input")
}

Large Input

When encoding large strings, it's essential to consider the performance implications. The EncodeToString function will allocate a new byte slice to store the encoded data, which can lead to memory issues if the input is extremely large. To mitigate this, you can use a streaming approach, where you encode the input in chunks.

const chunkSize = 1024
data := strings.Repeat("Hello, World!", 1000)
encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
for i := 0; i < len(data); i += chunkSize {
	chunk := data[i:min(i+chunkSize, len(data))]
	encoder.Write([]byte(chunk))
}
encoder.Close()

Unicode/Special Characters

The EncodeToString function will correctly encode Unicode characters and special characters, as it treats the input as a byte slice.

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

Common Mistakes

Mistake 1: Not converting the input to a byte slice

// Wrong
encoded := base64.StdEncoding.EncodeToString(data)
// Correct
encoded := base64.StdEncoding.EncodeToString([]byte(data))

Mistake 2: Not handling errors

// Wrong
data := (*string)(nil)
encoded := base64.StdEncoding.EncodeToString([]byte(*data))
// Correct
data := (*string)(nil)
if data != nil {
	encoded := base64.StdEncoding.EncodeToString([]byte(*data))
	fmt.Println(encoded)
} else {
	fmt.Println("Error: invalid input")
}

Mistake 3: Not considering performance implications

// Wrong
data := strings.Repeat("Hello, World!", 1000)
encoded := base64.StdEncoding.EncodeToString([]byte(data))
// Correct
const chunkSize = 1024
data := strings.Repeat("Hello, World!", 1000)
encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
for i := 0; i < len(data); i += chunkSize {
	chunk := data[i:min(i+chunkSize, len(data))]
	encoder.Write([]byte(chunk))
}
encoder.Close()

Performance Tips

Tip 1: Use the StdEncoding encoder

The StdEncoding encoder is the most efficient encoder provided by the encoding/base64 package. It uses a lookup table to encode the input, which makes it faster than the RawStdEncoding encoder.

encoder := base64.StdEncoding

Tip 2: Use a streaming approach for large inputs

When encoding large strings, use a streaming approach to avoid allocating a large byte slice. This can be done using the NewEncoder function.

const chunkSize = 1024
data := strings.Repeat("Hello, World!", 1000)
encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
for i := 0; i < len(data); i += chunkSize {
	chunk := data[i:min(i+chunkSize, len(data))]
	encoder.Write([]byte(chunk))
}
encoder.Close()

Tip 3: Avoid unnecessary allocations

When encoding a string, avoid allocating a new byte slice if the input is already a byte slice.

data := []byte("Hello, World!")
encoded := base64.StdEncoding.EncodeToString(data)

FAQ

Q: What is the difference between StdEncoding and RawStdEncoding?

A: StdEncoding is a more efficient encoder that uses a lookup table, while RawStdEncoding is a simpler encoder that uses a switch statement.

Q: How do I encode a large string efficiently?

A: Use a streaming approach with the NewEncoder function to avoid allocating a large byte slice.

Q: What happens if I pass a nil pointer to the EncodeToString function?

A: The function will panic. You should add error checking before calling the function.

Q: Can I use Base64 encoding for Unicode characters?

A: Yes, the EncodeToString function will correctly encode Unicode characters.

Q: How do I handle errors when encoding a string?

A: You can add error checking before calling the EncodeToString function, or use a streaming approach with the NewEncoder function.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp