Base64 in Go / Golang
Base64 encoding and decoding is a common task in many Go applications, especially those involving web protocols or binary data transfer. In Go, the encoding/base64 package provides functionality for base64 encoding and decoding. This package implements the RFC 4648 specification for base64 encoding with support for padding, URL and filename safe alphabets, and decoding of both standard and URL-encoded input. In this page, we will explore how to use the encoding/base64 package to perform base64 encoding and decoding in Go.
Encoding
In this example, the encoding/base64 package is imported and the StdEncoding function is used to encode a string to base64. The EncodeToString function takes a byte slice as input and returns the base64-encoded string. The encoded string is then printed to the console using the fmt.Println function.
1
2
3
4
5
6
7
8
9
10
11
12
package main
import (
"encoding/base64"
"fmt"
)
func main() {
str := "hello world"
encoded := base64.StdEncoding.EncodeToString([]byte(str))
fmt.Println(encoded) // aGVsbG8gd29ybGQ=
}
Decoding
To decode a base64 encoded string in Go, we can use the base64.StdEncoding.DecodeString() function. This function takes a base64 encoded string as input and returns the decoded byte slice. Here's an example code snippet that shows how to decode a base64 encoded string in Go:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
import (
"encoding/base64"
"fmt"
)
func main() {
encodedStr := "aGVsbG8gd29ybGQ="
decodedBytes, err := base64.StdEncoding.DecodeString(encodedStr)
if err != nil {
panic(err)
}
decodedStr := string(decodedBytes)
fmt.Println(decodedStr) // hello world
}
The Golang Base64 Package
Go has a built-in base64 package that provides efficient encoding and decoding of base64 data. One unique aspect of Go's implementation is that it can encode and decode directly from and to byte slices, making it easy to work with raw binary data. Additionally, the base64 package provides several encoding and decoding variants, such as URLEncoding and RawURLEncoding, that allow for encoding and decoding of URL-safe base64 data. Overall, Go's base64 package provides a simple and efficient way to work with base64 data in Go programs.