Developer Documentation
Go
Updated September 19, 2026

Base64 Encoding and Decoding in Go

Encode and decode Base64 safely, including UTF-8 text and binary data in Go.

Base64 converts binary data to printable ASCII text. It is useful for transport and embedding, but it is an encoding format, not encryption.

Quick Start#

The following example uses the standard Go API or a widely used package for this task.

Quick start#

Go
1package main23import (4    "encoding/base64"5    "fmt"6)78func main() {9    encoded := base64.StdEncoding.EncodeToString([]byte("Hello ToolPorta"))10    decoded, err := base64.StdEncoding.DecodeString(encoded)11    if err != nil { panic(err) }1213    fmt.Println(encoded)14    fmt.Println(string(decoded))15}

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

URL-safe Base64#

Go
1token := base64.RawURLEncoding.EncodeToString([]byte("token bytes"))2restored, err := base64.RawURLEncoding.DecodeString(token)3if err != nil { panic(err) }4_ = restored

Important Notes#

Choose StdEncoding, URLEncoding, or their raw unpadded variants deliberately; they are not interchangeable in every protocol.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement Base64 in other languages: