Encode Unpadded URL Tokens With RawURLEncoding
Encode binary tokens cleanly with base64.RawURLEncoding and hex.EncodeToString, showing how unpadded decoders reject trailing equals signs.
Code
package main
import (
"encoding/base64"
"encoding/hex"
"fmt"
)
func main() {
raw := []byte{0xde, 0xad, 0xbe, 0xef, 0xfb, 0xff, 0x10}
// RawURLEncoding drops '=' padding and swaps '+/' for '-_'
token := base64.RawURLEncoding.EncodeToString(raw)
fingerprint := hex.EncodeToString(raw[:4])
fmt.Printf("token=%s (len=%d)\n", token, len(token))
fmt.Printf("hex prefix=%s\n", fingerprint)
decoded, err := base64.RawURLEncoding.DecodeString(token)
if err != nil {
fmt.Println("decode failed:", err)
return
}
fmt.Printf("roundtrip match=%t\n", string(decoded) == string(raw))
// Raw encodings strictly reject trailing '=' padding
_, padErr := base64.RawURLEncoding.DecodeString(token + "=")
fmt.Printf("padded input rejected=%t\n", padErr != nil)
}Runtime walkthrough — Encode Unpadded URL Tokens With RawURLEncoding
Everything happens inside the function main.
Error handling is inline: 1 place test err != nil and branch immediately.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
Look first at the signature func main()
Stdout emits prefixed indicators — token=, hex prefix=, decode failed: — when the file runs.
Key statements
if err != nil {
fmt.Println("decode failed:", err)
return
}
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Base64 Encoder & DecoderEncode text to Base64 and decode Base64 back to text with UTF-8 support. Handles Unicode characters correctly using TextEncoder and TextDecoder APIs.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.
FAQ
- What does Encode Unpadded URL Tokens With RawURLEncoding print when run?
- Execute the whole file; each printed line is prefixed with a label like `token=`, `hex prefix=`, `decode failed:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.