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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Use crypto/rand rather than math/rand whenever the output must be unguessable, like session identifiers.
- 2RawURLEncoding produces token strings safe to drop into URLs and cookies without extra escaping.
- 3Offering both a returning and a panicking variant lets callers choose between recoverable and fatal failure.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/generating-secure-random-tokens-in-go-explained-go-67c3/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.