The uuid package generates and inspects UUIDs (Universally Unique Identifiers) based on RFC 4122 and DCE 1.1: Authentication and Security Services. It provides comprehensive UUID generation for versions 1, 2, 3, 4, 5, 6, and 7, along with parsing, validation, and inspection capabilities. The UUID type is implemented as a 16-byte array for performance and to allow UUIDs as map keys.
go get github.com/google/uuidimport "github.com/google/uuid"import (
"fmt"
"github.com/google/uuid"
)
// Generate a new random UUID (Version 4)
id := uuid.New()
fmt.Println(id.String()) // e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// Parse a UUID string
parsed, err := uuid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479")
if err != nil {
// Handle error
}
// Use UUID as map key
data := make(map[uuid.UUID]string)
data[id] = "some value"The package provides several types for working with UUIDs.
// UUID is a 128 bit (16 byte) Universal Unique IDentifier
type UUID [16]byte
// Version represents a UUID's version
type Version byte
// Variant represents a UUID's variant
type Variant byte
// Domain represents a Version 2 domain
type Domain byte
// Time represents time as number of 100's of nanoseconds since 15 Oct 1582
type Time int64
// NullUUID represents a UUID that may be null (for SQL NULL handling)
type NullUUID struct {
UUID UUID
Valid bool // Valid is true if UUID is not NULL
}
// UUIDs is a slice of UUID types
type UUIDs []UUIDPredefined constants for UUID variants, domains, and well-known namespaces.
// Variant constants
const (
Invalid = Variant(iota) // Invalid UUID
RFC4122 // The variant specified in RFC4122
Reserved // Reserved, NCS backward compatibility
Microsoft // Reserved, Microsoft backward compatibility
Future // Reserved for future definition
)
// Domain constants for DCE Security (Version 2) UUIDs
const (
Person = Domain(0)
Group = Domain(1)
Org = Domain(2)
)Well-known namespace UUIDs and special values.
var (
// Well-known namespace IDs for name-based UUIDs
NameSpaceDNS UUID // 6ba7b810-9dad-11d1-80b4-00c04fd430c8
NameSpaceURL UUID // 6ba7b811-9dad-11d1-80b4-00c04fd430c8
NameSpaceOID UUID // 6ba7b812-9dad-11d1-80b4-00c04fd430c8
NameSpaceX500 UUID // 6ba7b814-9dad-11d1-80b4-00c04fd430c8
// Special UUID values
Nil UUID // Empty UUID, all zeros
Max UUID // All 128 bits set to 1
)Generate random UUIDs. This is the most commonly used UUID version and is recommended for general use.
// New creates a new random UUID or panics
// Equivalent to Must(NewRandom())
func New() UUID
// NewString creates a new random UUID and returns it as a string or panics
// Equivalent to New().String()
func NewString() string
// NewRandom returns a Random (Version 4) UUID
// Returns error if random data cannot be generated
func NewRandom() (UUID, error)
// NewRandomFromReader returns a UUID based on bytes read from io.Reader
func NewRandomFromReader(r io.Reader) (UUID, error)Usage Example:
// Simple usage - panics on error
id := uuid.New()
// Get as string directly
idStr := uuid.NewString()
// With error handling
id, err := uuid.NewRandom()
if err != nil {
// Handle error
}
// From custom random source
import "crypto/rand"
id, err := uuid.NewRandomFromReader(rand.Reader)Generate time-ordered UUIDs based on Unix Epoch timestamp with improved entropy. Version 7 is recommended over Version 1 and 6 for new applications requiring time-ordered UUIDs.
// NewV7 returns a Version 7 UUID based on current time (Unix Epoch)
// Uses randomness pool if enabled with EnableRandPool
func NewV7() (UUID, error)
// NewV7FromReader returns a Version 7 UUID using provided io.Reader for random bits
func NewV7FromReader(r io.Reader) (UUID, error)Usage Example:
// Generate time-ordered UUID
id, err := uuid.NewV7()
if err != nil {
// Handle error
}
// With custom random source
id, err := uuid.NewV7FromReader(rand.Reader)Generate time-based UUIDs using MAC address and timestamp. Suitable for legacy compatibility but Version 7 is recommended for new applications.
// NewUUID returns a Version 1 UUID based on current NodeID, clock sequence, and time
// Automatically sets NodeID and clock sequence if not already set
func NewUUID() (UUID, error)Usage Example:
id, err := uuid.NewUUID()
if err != nil {
// Handle error - may occur if time or NodeID cannot be determined
}Generate Version 6 UUIDs, which are field-compatible with Version 1 but reordered for improved database locality.
// NewV6 returns a Version 6 UUID based on current NodeID, clock sequence, and time
// Automatically sets NodeID (random if cannot be determined) and clock sequence
func NewV6() (UUID, error)Usage Example:
id, err := uuid.NewV6()
if err != nil {
// Handle error
}Generate DCE Security UUIDs with domain and ID information.
// NewDCESecurity returns a DCE Security (Version 2) UUID
// Domain should be Person, Group, or Org
// On POSIX: id is UID for Person domain, GID for Group domain
func NewDCESecurity(domain Domain, id uint32) (UUID, error)
// NewDCEPerson returns DCE Security UUID in person domain with os.Getuid
func NewDCEPerson() (UUID, error)
// NewDCEGroup returns DCE Security UUID in group domain with os.Getgid
func NewDCEGroup() (UUID, error)Usage Example:
// Using POSIX user ID
id, err := uuid.NewDCEPerson()
// Using POSIX group ID
id, err := uuid.NewDCEGroup()
// Custom domain and ID
id, err := uuid.NewDCESecurity(uuid.Person, 1000)Generate name-based UUIDs using MD5 (Version 3) or SHA1 (Version 5) hashing.
// NewMD5 returns a new MD5 (Version 3) UUID based on namespace and data
func NewMD5(space UUID, data []byte) UUID
// NewSHA1 returns a new SHA1 (Version 5) UUID based on namespace and data
func NewSHA1(space UUID, data []byte) UUID
// NewHash returns a UUID derived from hash of space concatenated with data
// Used to implement NewMD5 and NewSHA1, or for custom hash algorithms
func NewHash(h hash.Hash, space UUID, data []byte, version int) UUIDUsage Example:
import "hash"
// Generate name-based UUIDs (deterministic)
dnsBasedID := uuid.NewMD5(uuid.NameSpaceDNS, []byte("example.com"))
urlBasedID := uuid.NewSHA1(uuid.NameSpaceURL, []byte("https://example.com"))
// Same input always produces same UUID
id1 := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com"))
id2 := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com"))
// id1 == id2 is true
// Custom hash algorithm
import "crypto/sha256"
customID := uuid.NewHash(sha256.New(), uuid.NameSpaceDNS, []byte("data"), 5)Parse UUID strings and byte slices into UUID values.
// Parse decodes string into UUID or returns error
// Supports formats:
// - Standard: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// - URN: urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// - Raw hex: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// - Microsoft: {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
func Parse(s string) (UUID, error)
// ParseBytes is like Parse but parses a byte slice
func ParseBytes(b []byte) (UUID, error)
// MustParse is like Parse but panics if string cannot be parsed
// Useful for safe initialization of global variables
func MustParse(s string) UUID
// FromBytes creates UUID from byte slice (must be exactly 16 bytes)
func FromBytes(b []byte) (UUID, error)
// Must returns uuid if err is nil and panics otherwise
// Helper for safe initialization
func Must(uuid UUID, err error) UUIDUsage Example:
// Parse with error handling
id, err := uuid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479")
if err != nil {
// Handle parse error
}
// Parse various formats
id1, _ := uuid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479") // Standard
id2, _ := uuid.Parse("urn:uuid:f47ac10b-58cc-4372-a567-0e02b2c3d479") // URN
id3, _ := uuid.Parse("f47ac10b58cc4372a5670e02b2c3d479") // Raw hex
id4, _ := uuid.Parse("{f47ac10b-58cc-4372-a567-0e02b2c3d479}") // Microsoft
// Parse from bytes
idBytes := []byte("f47ac10b-58cc-4372-a567-0e02b2c3d479")
id, err := uuid.ParseBytes(idBytes)
// Create from 16-byte slice
rawBytes := []byte{0xf4, 0x7a, 0xc1, 0x0b, /* ... 16 bytes total */}
id, err := uuid.FromBytes(rawBytes)
// Safe initialization for globals (panics on error)
var namespaceMyApp = uuid.MustParse("f47ac10b-58cc-4372-a567-0e02b2c3d479")
// Helper for initialization
var id = uuid.Must(uuid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479"))Validate UUID strings without creating UUID objects.
// Validate returns error if s is not a properly formatted UUID
// Supports same formats as Parse
func Validate(s string) error
// IsInvalidLengthError checks if error is an invalid length error
func IsInvalidLengthError(err error) boolUsage Example:
// Validate without parsing
err := uuid.Validate("f47ac10b-58cc-4372-a567-0e02b2c3d479")
if err != nil {
// Invalid format
}
// Check specific error type
err = uuid.Validate("too-short")
if uuid.IsInvalidLengthError(err) {
// Handle invalid length specifically
}Convert UUIDs to string representations.
// String returns string form: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// Returns empty string if uuid is invalid
func (uuid UUID) String() string
// URN returns RFC 2141 URN form: urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// Returns empty string if uuid is invalid
func (uuid UUID) URN() stringUsage Example:
id := uuid.New()
// Standard format
str := id.String() // "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// URN format
urn := id.URN() // "urn:uuid:f47ac10b-58cc-4372-a567-0e02b2c3d479"
// Direct usage in strings
fmt.Printf("ID: %s\n", id) // Calls String() methodInspect UUID properties and extract embedded information.
// Version returns the version of uuid
func (uuid UUID) Version() Version
// Variant returns the variant encoded in uuid
func (uuid UUID) Variant() Variant
// Time returns time in 100s of nanoseconds since 15 Oct 1582
// Only defined for version 1, 2, 6, and 7 UUIDs
func (uuid UUID) Time() Time
// ClockSequence returns clock sequence encoded in uuid
// Only well defined for version 1 and 2 UUIDs
func (uuid UUID) ClockSequence() int
// NodeID returns 6 byte node id encoded in uuid
// Returns nil if uuid is not valid
// Only well defined for version 1 and 2 UUIDs
func (uuid UUID) NodeID() []byte
// Domain returns domain for a Version 2 UUID
func (uuid UUID) Domain() Domain
// ID returns id for a Version 2 UUID
func (uuid UUID) ID() uint32Usage Example:
id, _ := uuid.NewV7()
// Check version and variant
ver := id.Version() // Version(7)
variant := id.Variant() // RFC4122
// Extract time from time-based UUIDs (v1, v2, v6, v7)
if ver == 7 || ver == 1 {
t := id.Time()
sec, nsec := t.UnixTime() // Convert to Unix time
}
// Extract clock sequence from v1/v2
v1ID, _ := uuid.NewUUID()
seq := v1ID.ClockSequence()
// Extract node ID from v1/v2
nodeID := v1ID.NodeID() // []byte of length 6
// Extract domain and ID from v2
v2ID, _ := uuid.NewDCEPerson()
domain := v2ID.Domain() // Person
userID := v2ID.ID() // uint32 user IDGet string representations of Version, Variant, and Domain types.
// String returns string representation of version (e.g., "VERSION_4")
func (v Version) String() string
// String returns string representation of variant (e.g., "RFC4122")
func (v Variant) String() string
// String returns string representation of domain
func (d Domain) String() stringUsage Example:
id := uuid.New()
fmt.Println(id.Version().String()) // "VERSION_4"
fmt.Println(id.Variant().String()) // "RFC4122"
v2ID, _ := uuid.NewDCEPerson()
fmt.Println(v2ID.Domain().String()) // "Person"Convert UUID time values to Unix timestamps.
// UnixTime converts Time to Unix epoch (seconds and nanoseconds since 1 Jan 1970)
func (t Time) UnixTime() (sec, nsec int64)Usage Example:
id, _ := uuid.NewV7()
uuidTime := id.Time()
sec, nsec := uuidTime.UnixTime()
// Convert to time.Time
import "time"
timestamp := time.Unix(sec, nsec)Marshal and unmarshal UUIDs in binary format.
// MarshalBinary implements encoding.BinaryMarshaler
// Returns 16-byte binary representation
func (uuid UUID) MarshalBinary() ([]byte, error)
// UnmarshalBinary implements encoding.BinaryUnmarshaler
// Expects exactly 16 bytes
func (uuid *UUID) UnmarshalBinary(data []byte) errorUsage Example:
id := uuid.New()
// Encode to binary
data, err := id.MarshalBinary()
// data is []byte of length 16
// Decode from binary
var decoded uuid.UUID
err = decoded.UnmarshalBinary(data)Marshal and unmarshal UUIDs in text format.
// MarshalText implements encoding.TextMarshaler
// Returns UUID in standard string format
func (uuid UUID) MarshalText() ([]byte, error)
// UnmarshalText implements encoding.TextUnmarshaler
// Accepts same formats as Parse
func (uuid *UUID) UnmarshalText(data []byte) errorUsage Example:
id := uuid.New()
// Encode to text
text, err := id.MarshalText()
// text is []byte containing "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
// Decode from text
var decoded uuid.UUID
err = decoded.UnmarshalText([]byte("f47ac10b-58cc-4372-a567-0e02b2c3d479"))Store and retrieve UUIDs in SQL databases.
// Scan implements sql.Scanner for reading UUIDs from databases
// Supports database types that map to string and []byte
func (uuid *UUID) Scan(src interface{}) error
// Value implements sql.Valuer for writing UUIDs to databases
// Currently maps UUIDs to strings
func (uuid UUID) Value() (driver.Value, error)Usage Example:
import "database/sql"
// Store UUID in database
id := uuid.New()
_, err := db.Exec("INSERT INTO users (id, name) VALUES (?, ?)", id, "John")
// Retrieve UUID from database
var userID uuid.UUID
var name string
err = db.QueryRow("SELECT id, name FROM users WHERE name = ?", "John").Scan(&userID, &name)Handle NULL UUIDs in SQL databases.
// Scan implements sql.Scanner for NullUUID
func (nu *NullUUID) Scan(value interface{}) error
// Value implements driver.Valuer for NullUUID
func (nu NullUUID) Value() (driver.Value, error)
// MarshalJSON implements json.Marshaler for NullUUID
func (nu NullUUID) MarshalJSON() ([]byte, error)
// UnmarshalJSON implements json.Unmarshaler for NullUUID
func (nu *NullUUID) UnmarshalJSON(data []byte) error
// MarshalText implements encoding.TextMarshaler for NullUUID
func (nu NullUUID) MarshalText() ([]byte, error)
// UnmarshalText implements encoding.TextUnmarshaler for NullUUID
func (nu *NullUUID) UnmarshalText(data []byte) error
// MarshalBinary implements encoding.BinaryMarshaler for NullUUID
func (nu NullUUID) MarshalBinary() ([]byte, error)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for NullUUID
func (nu *NullUUID) UnmarshalBinary(data []byte) errorUsage Example:
import "database/sql"
// Handle potentially NULL UUID in database
var u uuid.NullUUID
err := db.QueryRow("SELECT id FROM users WHERE name = ?", "John").Scan(&u)
if u.Valid {
// Use u.UUID
fmt.Println("User ID:", u.UUID)
} else {
// Handle NULL
fmt.Println("No user ID")
}
// Insert NULL UUID
nullID := uuid.NullUUID{Valid: false}
_, err = db.Exec("INSERT INTO users (id, name) VALUES (?, ?)", nullID, "Jane")
// JSON marshaling
import "encoding/json"
data, err := json.Marshal(u) // null if not Valid, UUID string if ValidWork with slices of UUIDs.
// Strings returns string slice containing string form of each UUID
func (uuids UUIDs) Strings() []stringUsage Example:
ids := uuid.UUIDs{
uuid.New(),
uuid.New(),
uuid.New(),
}
// Convert all to strings
strings := ids.Strings()
for _, s := range strings {
fmt.Println(s)
}Configure the random number generator for UUID generation.
// SetRand sets random number generator to r (io.Reader)
// Passing nil sets to default generator (crypto/rand.Reader)
// Panics if r.Read returns error when generating UUIDs
func SetRand(r io.Reader)
// EnableRandPool enables internal randomness pool for Version 4 UUID generation
// May improve throughput but stores random data on heap
// NOT thread-safe - call only when no UUIDs are being generated concurrently
func EnableRandPool()
// DisableRandPool disables the randomness pool
// NOT thread-safe - call only when no UUIDs are being generated concurrently
func DisableRandPool()Usage Example:
import "crypto/rand"
// Use custom random source
SetRand(myCustomReader)
// Reset to default
SetRand(nil)
// Enable pool for better performance (at initialization)
uuid.EnableRandPool()
// Disable pool
uuid.DisableRandPool()Configure the Node ID used for Version 1 and 6 UUIDs.
// NodeID returns slice of copy of current Node ID
// Sets Node ID automatically if not already set
func NodeID() []byte
// SetNodeID sets Node ID for Version 1 UUIDs
// Uses first 6 bytes of id
// Returns false if id has less than 6 bytes
func SetNodeID(id []byte) bool
// SetNodeInterface selects hardware address for Version 1 UUIDs
// Empty string selects first usable interface or random Node ID
// Returns false if named interface cannot be found
func SetNodeInterface(name string) bool
// NodeInterface returns name of interface from which NodeID was derived
// Returns "user" if NodeID was set by SetNodeID
func NodeInterface() stringUsage Example:
// Get current Node ID (auto-set if needed)
nodeID := uuid.NodeID()
// Set custom Node ID
customID := []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}
uuid.SetNodeID(customID)
// Use specific network interface
uuid.SetNodeInterface("eth0")
// Use first available interface (or random)
uuid.SetNodeInterface("")
// Check which interface is being used
iface := uuid.NodeInterface()Configure the clock sequence for Version 1 and 6 UUIDs.
// ClockSequence returns current clock sequence
// Generates new random sequence if not already set
// Only used for Version 1 UUIDs
func ClockSequence() int
// SetClockSequence sets clock sequence to lower 14 bits of seq
// Setting to -1 causes new sequence to be generated
func SetClockSequence(seq int)
// GetTime returns current Time (100s of nanoseconds since 15 Oct 1582)
// and clock sequence, adjusting clock sequence as needed
func GetTime() (Time, uint16, error)Usage Example:
// Get current clock sequence
seq := uuid.ClockSequence()
// Set custom clock sequence
uuid.SetClockSequence(12345)
// Reset to random sequence
uuid.SetClockSequence(-1)
// Get current time and sequence
t, seq, err := uuid.GetTime()
if err != nil {
// Handle error
}