Skip to content

Go Base64 Encoding

Base64 encoding allows you to represent binary data (like images or encrypted files) as a plain text string. This is useful for sending data over protocols that only support text, like HTTP headers or email.

1. Basic Encoding and Decoding

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    data := "hello go"

    // 1. Encode simple string
    // Standard Base64 uses + and / characters
    encoded := base64.StdEncoding.EncodeToString([]byte(data))
    fmt.Println(encoded) // aGVsbG8gZ28=

    // 2. Decode back to original
    decoded, _ := base64.StdEncoding.DecodeString(encoded)
    fmt.Println(string(decoded)) // hello go
}

2. URL-Safe Encoding

Standard Base64 contains characters like + and / that have special meanings in URLs. Use URLEncoding to swap them for - and _.

1
2
3
// Use this for URLs or filenames
uEnc := base64.URLEncoding.EncodeToString([]byte(data))
fmt.Println(uEnc)

3. Encodings without Padding

By default, Base64 adds = at the end to make the string a specific length. You can remove this using the Raw variants.

1
2
3
// No '=' at the end
rawEnc := base64.RawStdEncoding.EncodeToString([]byte(data))
fmt.Println(rawEnc)

Why use Base64?

  1. Transport Safe: Binary data can contain "invisible" control characters that break text-based protocols. Base64 is guaranteed safe.
  2. Standards: It's the standard for Basic Auth, JWT tokens, and embedding images in HTML.
  3. Data URLs: You can represent a whole file inside a single string: data:image/png;base64,iVBORw....