Base64 StdEncoding Versus URLEncoding

The same bytes encode differently under base64.StdEncoding and base64.URLEncoding: +/ become -_ in the URL alphabet, and Raw variants drop = padding.

GoData Integrity

Code

snippet
package main

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"strings"
)

func main() {
	// bytes chosen so the std alphabet needs '+' and '/'
	payload := []byte{0xfb, 0xef, 0xbe, 0x00, 0xff}

	stdEnc := base64.StdEncoding.EncodeToString(payload)
	urlEnc := base64.URLEncoding.EncodeToString(payload)
	fmt.Println("std :", stdEnc)
	fmt.Println("url :", urlEnc)
	fmt.Println("std uses + :", strings.Contains(stdEnc, "+"))
	fmt.Println("url uses - :", strings.Contains(urlEnc, "-"))

	// Raw variants drop '=' padding, which is what JWT segments use
	rawURL := base64.RawURLEncoding.EncodeToString(payload)
	fmt.Printf("raw url: %s (len %d vs padded %d)\n", rawURL, len(rawURL), len(urlEnc))

	// versus: decoding only succeeds with the alphabet that encoded the bytes
	back, err := base64.URLEncoding.DecodeString(urlEnc)
	if err != nil {
		panic(err)
	}
	fmt.Println("roundtrip ok:", bytes.Equal(back, payload))
}

How it works

Base64 StdEncoding Versus URLEncoding comes down to the function main.

Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

What to watch for

  • Nothing external — every call lands on the language’s built-in API surface.
  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Using it

Signature: func main()

The demo output is labeled (std :, url :, std uses + :), so the printed output reads as a trace of the operations performed.

The key statements, annotated

if err != nil {
	panic(err)
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
There are no error returns here: a non-nil `err` reaches `panic(err)` immediately.
What does Base64 StdEncoding Versus URLEncoding print when run?
Run it as a complete program — the output lines carry labels such as `std :`, `url :`, `std uses + :`.