UUID generation in Go - cover art

Comparisons 13 min read

UUID generation in Go

October 21, 2026 · 13 min read

Go services use UUIDs for request tracing, primary keys, and correlation IDs. The de facto package is github.com/google/uuid, which implements RFC 4122 generation and parsing with a small API surface. This article shows the calls you need and the mistakes that show up when IDs cross HTTP and MongoDB boundaries.

The google/uuid package

Add the module with go get github.com/google/uuid. Types are value-based uuid.UUID (16 bytes) with String() for canonical hyphenated hex and MarshalText for JSON. The package documents which functions are cryptographically random versus name-based (v3/v5).

import "github.com/google/uuid"

id := uuid.New()        // random UUID (version 4)
s := id.String()        // "550e8400-e29b-41d4-a716-446655440000"
parsed, err := uuid.Parse(s)

uuid.New() and version 4

uuid.New() and uuid.NewRandom() produce version 4 identifiers from a cryptographically secure source. For most microservices, that is the right default: opaque, no coordination, and safe to expose in URLs. Avoid uuid.NewUUID() (time-based v1) unless you explicitly need MAC-derived node IDs.

Parsing, MustParse, and validation

Use uuid.Parse for user input and return 400 on error - do not MustParse on request paths. Accept only canonical 36-character hyphenated form unless you normalize elsewhere. For defensive checks, compare parsed bytes with a regex at the HTTP layer and again in domain logic.

Databases, JSON, and REST

Store UUIDs as BINARY(16) or native UUID types when the database supports them; string columns work but waste space and invite case drift. In JSON APIs emit lowercase hyphenated strings. Cross-check partner IDs with the UUID generator and UUID validator when debugging integration mismatches.

Common Go UUID pitfalls

Logging %x on the byte array without hyphens confuses operators comparing to RFC strings. Reusing v1 UUIDs across hosts can leak hardware hints. When calling MongoDB from Go, confirm BSON subtype 0x04 endianness matches your driver - see MongoDB UUID articles if hex looks “byte-swapped.”

FAQ

Does uuid.New() return version 4?
Yes. google/uuid documents New() as a random (v4) UUID from a secure source.
Should I store UUID as string or []byte in Go?
Use uuid.UUID (16 bytes) in memory; persist as BINARY(16) or char(36) per database conventions.
How do I generate UUID v7 in Go?
Use a v7-capable library or generate externally until your stack standardizes on an RFC draft implementation.

Related: UUID generation in Java · UUIDs in REST APIs · UUID security considerations · How UUIDs work internally

Browse all tools