UUID Generator — Go source
Generate RFC 4122 v4 UUIDs with crypto-grade randomness. Bulk generate, copy all, toggle format (uppercase / no hyphens).
This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package uuid is the Go twin of CosmoDev's src/lib/uuid.ts (dual source: the
// web lib is TypeScript, the CLI lib is Go — kept in lock-step). Pure in shape
// and never panics, crypto-grade random. The table-driven tests in uuid_test.go
// share vectors with src/lib/uuid.test.ts so the two implementations are held
// to the same contract.
//
// UUIDv4 mirrors the TS lib exactly: 16 crypto-random bytes, the version nibble
// set to 4 (b[6] = (b[6] & 0x0f) | 0x40), the variant nibble set to 0b10
// (b[8] = (b[8] & 0x3f) | 0x80), then formatted into 4-2-2-2-6 hex groups.
package uuid
import (
"crypto/rand"
"fmt"
)
// UUIDv4 returns a freshly generated RFC 4122 version 4 UUID string. It is the
// Go twin of uuidv4() in src/lib/uuid.ts and must agree with it on every shared
// contract: 36 chars, version nibble '4', variant nibble in {8,9,a,b}, and
// uniqueness across batches. Randomness is crypto-grade via crypto/rand,
// matching the TS lib's crypto.getRandomValues fallback path.
//
// It never panics: if the system entropy source is unavailable it returns an
// empty string (a zero-value) rather than crashing. The TS lib would throw on a
// failing getRandomValues, but a twin must never panic — return a zero-value
// mirroring the failure mode.
func UUIDv4() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "" // entropy unavailable — zero-value, never panic
}
b[6] = (b[6] & 0x0f) | 0x40 // version 4
b[8] = (b[8] & 0x3f) | 0x80 // variant 0b10 (RFC 4122)
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →