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
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 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.