Go by Example

Base64 Encoding

Choose URL-safe Base64 encoding, handle decode errors, and stream large payloads with NewEncoder.

Base64 represents bytes as printable text; it is an encoding, not encryption. encoding/base64 provides standard and URL-safe alphabets.

Use RawURLEncoding for URL-safe data without equals padding. Decode with the same encoding and handle malformed input.

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

For large inputs, Base64 output is about one third larger and provides no confidentiality. Use URLEncoding or RawURLEncoding where URL-safe text is required. For large streams, use NewEncoder and close it to flush padding. For tokens, generate the source bytes with crypto/rand before encoding them.

Enjoyed this? Get more software craft delivered to your inbox.