Go’s encoding/base64 package provides four ready-made encodings and lets you define custom ones.
| Variable | Alphabet | Padding |
|---|---|---|
base64.StdEncoding |
+ / |
yes |
base64.RawStdEncoding |
+ / |
no |
base64.URLEncoding |
- _ |
yes |
base64.RawURLEncoding |
- _ |
no (JWT, URLs) |
Strings
package main
import (
"encoding/base64"
"fmt"
)
func main() {
s := base64.StdEncoding.EncodeToString([]byte("Grüße 👋"))
fmt.Println(s) // R3LDvMOfZSDwn5GL
b, err := base64.StdEncoding.DecodeString(s)
if err != nil {
panic(err) // illegal base64 data at input byte N
}
fmt.Println(string(b))
}
Go strings are UTF-8, so no conversion step is needed.
Decode errors
illegal base64 data at input byte 12 gives the exact position of the problem. Typical causes: Base64URL input decoded with StdEncoding, missing padding (use the Raw variant), or a data URI prefix. The decoder ignores \r and \n but nothing else.
Strict mode
enc := base64.StdEncoding.Strict() // rejects non-zero trailing bits
Without it, QQ== and QR== both decode to A. Strict mode matters when Base64 values are compared or used as keys.
Streaming
in, _ := os.Open("big.bin")
out, _ := os.Create("big.b64")
w := base64.NewEncoder(base64.StdEncoding, out)
io.Copy(w, in)
w.Close() // flushes the final partial block and padding
Forgetting Close() silently drops the last 1–2 bytes. Decode streams with base64.NewDecoder(base64.StdEncoding, r).
Appending without allocations (Go 1.22+)
buf = base64.StdEncoding.AppendEncode(buf, data)
Check your output with the Base64 decoder.
Comments (0)
Questions, ideas or a bug in “Base64 in Go”? Leave a comment, rate the tool, or reply to others.
No comments yet. Be the first to share your feedback!