Base64 Encoding
Choose URL-safe Base64 encoding, handle decode errors, and stream large payloads with NewEncoder.
Base64 turns bytes, the small numeric pieces that make up data, into letters and numbers that can be written as text. It is an encoding, not encryption: anyone can decode it. The encoding/base64 package provides standard and URL-safe forms.
Use RawURLEncoding for URL-safe data without the = characters sometimes added at the end. Decode with the same encoding and report an error if the input is invalid.
package main
import (
"encoding/base64"
"fmt"
)
func main() {
encoded := base64.RawURLEncoding.EncodeToString([]byte("hello"))
decoded, err := base64.RawURLEncoding.DecodeString(encoded)
if err != nil {
panic(err)
}
fmt.Println(encoded, string(decoded))
}In production
Base64 output is about one third larger than the original data and does not keep that data secret. Use a URL-safe form when the text will appear in a URL. For a large input, NewEncoder converts pieces as they are written; close it so it can finish the encoded output. Use encryption when data must be kept private.