Base64 Encoding
encoding/base64 StdEncoding and URLEncoding for encode/decode, RawURLEncoding for padding-free tokens, and streaming encoders.
The encoding/base64 package encodes binary data as printable ASCII text. Two encodings are available: StdEncoding (uses + and /) and URLEncoding (uses - and _, safe in URLs).
base64.StdEncoding.EncodeToString encodes a byte slice to a base64 string. DecodeString reverses it, returning a byte slice and an error if the input is malformed.
package main
import (
"encoding/base64"
"fmt"
)
func main() {
data := []byte("user:secret-password")
encoded := base64.StdEncoding.EncodeToString(data)
fmt.Println(encoded) // dXNlcjpzZWNyZXQtcGFzc3dvcmQ=
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
panic(err)
}
fmt.Println(string(decoded)) // user:secret-password
}base64.URLEncoding replaces + with - and / with _, making the output safe to embed in URLs and filenames. base64.RawURLEncoding omits the = padding - used in JWT segments and URL-safe tokens.
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
)
func main() {
// Standard encoding - may produce + and / in output
std := base64.StdEncoding.EncodeToString([]byte{0xfb, 0xef, 0xff})
fmt.Println("std:", std) // ++//
// URL-safe encoding - replaces + with - and / with _
url := base64.URLEncoding.EncodeToString([]byte{0xfb, 0xef, 0xff})
fmt.Println("url:", url) // --__
// Generate a URL-safe random token (no padding)
buf := make([]byte, 24)
rand.Read(buf)
token := base64.RawURLEncoding.EncodeToString(buf)
fmt.Println("token:", token) // 32-char URL-safe token, no = padding
}For large payloads, wrap an io.Writer with base64.NewEncoder to stream encoding without buffering the entire output. Call Close() to flush any remaining bytes and write the final padding.
package main
import (
"encoding/base64"
"os"
"strings"
)
func main() {
enc := base64.NewEncoder(base64.StdEncoding, os.Stdout)
defer enc.Close()
r := strings.NewReader("streaming base64 example output")
buf := make([]byte, 8)
for {
n, err := r.Read(buf)
if n > 0 {
enc.Write(buf[:n])
}
if err != nil {
break
}
}
}In production
Use base64.URLEncoding (or base64.RawURLEncoding without padding) for URL-safe tokens and JWT segments - standard base64 uses + and / which are special characters in URLs and require percent-encoding. When size matters, note that base64 inflates data by approximately 33% (3 bytes become 4 characters). For generating random tokens (session IDs, CSRF tokens, API keys), fill a byte slice with crypto/rand.Read, then base64.RawURLEncoding.EncodeToString - 18 random bytes give 24 URL-safe characters with 144 bits of entropy, sufficient for most token use cases. Never roll a custom encoding for tokens; use the stdlib encoders to avoid subtle bugs with alphabet selection and padding.
Enjoyed this? Get more essays on software craft delivered to your inbox.
Subscribe free