go 32 lines · 5 steps

Generating secure random tokens in Go

A small package that turns cryptographically random bytes into URL-safe token strings.

Explained by highlit
1package token
2 
3import (
4 "crypto/rand"
5 "encoding/base64"
6 "fmt"
7)
8 
9func Generate(byteLen int) (string, error) {
10 if byteLen <= 0 {
11 return "", fmt.Errorf("token: byteLen must be positive, got %d", byteLen)
12 }
13 
14 buf := make([]byte, byteLen)
15 if _, err := rand.Read(buf); err != nil {
16 return "", fmt.Errorf("token: reading random bytes: %w", err)
17 }
18 
19 return base64.RawURLEncoding.EncodeToString(buf), nil
20}
21 
22func MustGenerate(byteLen int) string {
23 tok, err := Generate(byteLen)
24 if err != nil {
25 panic(err)
26 }
27 return tok
28}
29 
30func SessionID() (string, error) {
31 return Generate(32)
32}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Use crypto/rand rather than math/rand whenever the output must be unguessable, like session identifiers.
  2. 2RawURLEncoding produces token strings safe to drop into URLs and cookies without extra escaping.
  3. 3Offering both a returning and a panicking variant lets callers choose between recoverable and fatal failure.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Generating secure random tokens in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code