### Install uuid Package Source: https://github.com/google/uuid/blob/master/README.md Use this command to install the uuid package using go get. ```sh go get github.com/google/uuid ``` -------------------------------- ### UUID Package Testing Examples Source: https://github.com/google/uuid/blob/master/_autodocs/README.md Demonstrates how to test UUID parsing, database integration, and JSON serialization/deserialization. Ensure you have a database connection and JSON library available. ```go // Verify parsing works u, err := uuid.Parse("550e8400-e29b-41d4-a716-446655440000") if err != nil || u.String() != "550e8400-e29b-41d4-a716-446655440000" { t.Fatal("Parse/String roundtrip failed") } // Verify database integration var scanned uuid.UUID err = db.QueryRow("SELECT ?::uuid", u).Scan(&scanned) if scanned != u { t.Fatal("Database roundtrip failed") } // Verify JSON data, _ := json.Marshal(u) var j uuid.UUID json.Unmarshal(data, &j) if j != u { t.Fatal("JSON roundtrip failed") } ``` -------------------------------- ### UUID Versions Quick Lookup Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Provides examples for generating different versions of UUIDs, including random (v4), time-ordered (v7), deterministic (v5, v3), time-based (v1, v6), and legacy (v2) versions. ```go // Random (most common) u := uuid.New() // v4 // Time-ordered (modern, RFC recommended) u, _ := uuid.NewV7() // v7 // Deterministic from data u := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com")) // v5 // Time-based (legacy, use v6/v7 instead) u, _ := uuid.NewUUID() // v1 // Sortable time-based u, _ := uuid.NewV6() // v6 u, _ := uuid.NewV6WithTime(&customTime) // v6 with custom time // Deterministic MD5 (deprecated, use v5) u := uuid.NewMD5(uuid.NameSpaceDNS, []byte("example.com")) // v3 // User/Group domain (legacy) u, _ := uuid.NewDCESecurity(uuid.Person, 501) // v2 u, _ := uuid.NewDCEPerson() // v2 with current user u, _ := uuid.NewDCEGroup() // v2 with current group ``` -------------------------------- ### Get and Set Clock Sequence Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/time-and-node-management.md Manages the clock sequence for Version 1 UUIDs. `ClockSequence()` returns the current sequence (generating a random one on first call), while `SetClockSequence()` allows setting a specific sequence or generating a new random one. ```go seq := uuid.ClockSequence() fmt.Printf("Clock Sequence: %d\n", seq) // Usually 0-16383 (14-bit value) ``` ```go // Generate random sequence uuid.SetClockSequence(-1) // Set specific sequence uuid.SetClockSequence(1234) // Retrieve the set value seq := uuid.ClockSequence() fmt.Println(seq) ``` -------------------------------- ### ErrInvalidURNPrefix Variable Source: https://github.com/google/uuid/blob/master/_autodocs/errors.md This error occurs when a 45-character input is intended as a URN but does not start with the required 'urn:uuid:' prefix. ```go var ErrInvalidURNPrefix = URNPrefixError{} ``` -------------------------------- ### Extract UUID Version Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/utilities.md Get the version number from a UUID. The version indicates the algorithm used to generate the UUID. ```go u := uuid.New() v := u.Version() fmt.Println(v) // 4 (random) u, _ := uuid.NewUUID() v = u.Version() fmt.Println(v) // 1 (time-based) // Check version type if u.Version() == 4 { fmt.Println("Random UUID") } ``` -------------------------------- ### Migrate from v1 to v6 to v7 Source: https://github.com/google/uuid/blob/master/_autodocs/version-comparison.md Demonstrates the step-by-step migration path from Version 1 UUIDs to Version 6 (for better sort order) and finally to Version 7 (the modern recommended version). ```go // Step 1: Generate v1 u1, _ := uuid.NewUUID() // Step 2: Migrate to v6 (better sort order, compatible) u6, _ := uuid.NewV6() // Step 3: Migrate to v7 (modern, recommended) u7, _ := uuid.NewV7() ``` -------------------------------- ### Database Integration for UUIDs Source: https://github.com/google/uuid/blob/master/_autodocs/README.md Demonstrates how to read and write UUIDs to and from a SQL database using Scan and Exec. Supports optional UUIDs with NullUUID. ```Go // Reading from database var u uuid.UUID err := db.QueryRow("SELECT id FROM users").Scan(&u) // Writing to database _, err := db.Exec("INSERT INTO users (id) VALUES (?)", u) // Optional UUID (NULL-safe) var nu uuid.NullUUID err := db.QueryRow("SELECT optional_id FROM table").Scan(&nu) if nu.Valid { fmt.Println(nu.UUID) } ``` -------------------------------- ### Get Node Interface Name Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/time-and-node-management.md Retrieves the name of the network interface used for Node ID initialization. Useful for debugging and understanding how the Node ID was determined. ```go ifname := uuid.NodeInterface() fmt.Printf("Node interface: %s\n", ifname) // Determine initialization method if ifname == "user" { fmt.Println("Node ID was explicitly set") } else if ifname == "random" { fmt.Println("Node ID was randomly generated") } else { fmt.Printf("Node ID from hardware: %s\n", ifname) } ``` -------------------------------- ### Migrate from v3 (MD5) to v5 (SHA1) Source: https://github.com/google/uuid/blob/master/_autodocs/version-comparison.md Illustrates the migration from Version 3 (MD5) to Version 5 (SHA1) UUID generation. Version 5 uses a stronger hashing algorithm (SHA1) compared to Version 3's MD5. ```go // Old u := uuid.NewMD5(namespace, data) // v3, weak hash // New u := uuid.NewSHA1(namespace, data) // v5, stronger ``` -------------------------------- ### Get Node ID Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/time-and-node-management.md Retrieves the current 6-byte Node ID, auto-initializing it if it hasn't been set. The Node ID can be initialized from hardware interfaces or generated randomly. ```go nodeID := uuid.NodeID() fmt.Printf("Node ID: %x\n", nodeID) // Use in logging or diagnostics for _, b := range nodeID { fmt.Printf("%02x", b) } fmt.Println() ``` -------------------------------- ### Database Operations with UUIDs Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Demonstrates how to use UUIDs in database operations, including reading, writing, and handling NULL UUIDs using uuid.NullUUID. ```go import "database/sql" type User struct { ID uuid.UUID Name string } // Read from database var user User err := db.QueryRow("SELECT id, name FROM users WHERE id = ?", userID). Scan(&user.ID, &user.Name) // Write to database _, err := db.Exec( "INSERT INTO users (id, name) VALUES (?, ?)", uuid.New(), "Alice", ) // Handle NULL UUID (optional field) var nullableID uuid.NullUUID err := db.QueryRow("SELECT optional_id FROM table").Scan(&nullableID) if nullableID.Valid { fmt.Println("ID:", nullableID.UUID) } ``` -------------------------------- ### Get Current Time and Clock Sequence Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/time-and-node-management.md Retrieves the current time in 100-nanosecond intervals since 15 Oct 1582 and the current clock sequence. This is used internally for Version 1 and 6 UUID generation. ```go t, seq, err := uuid.GetTime() if err != nil { log.Fatal(err) } // For Version 1/6 UUID generation // These functions use GetTime internally u := uuid.Must(uuid.NewUUID()) u := uuid.Must(uuid.NewV6()) ``` -------------------------------- ### Format Version to String Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/utilities.md Convert a Version type to its string representation. Use this to display version information in a human-readable format. ```go v := uuid.Version(4) fmt.Println(v.String()) // "VERSION_4" v = uuid.Version(99) fmt.Println(v.String()) // "BAD_VERSION_99" ``` -------------------------------- ### Database Operations with UUIDs Source: https://github.com/google/uuid/blob/master/_autodocs/README.md Demonstrates inserting and querying user data with UUIDs in a database. It shows how to use UUIDs directly with database drivers that support scanning and value conversion. ```go type User struct { ID uuid.UUID Email string } user := User{ID: uuid.New(), Email: "user@example.com"} // Insert _, err := db.Exec( "INSERT INTO users (id, email) VALUES (?, ?)", user.ID, user.Email, ) // Query var found User db.QueryRow("SELECT id, email FROM users WHERE id = ?", someID). Scan(&found.ID, &found.Email) ``` -------------------------------- ### Create and Use Custom Namespaces Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Define a custom namespace using a known namespace (like URL) and a unique identifier. Then, use this custom namespace to generate deterministic UUIDs for specific entities like users. ```go // Create app-specific namespace appNamespace := uuid.NewSHA1(uuid.NameSpaceURL, []byte("https://myapp.io")) // Generate user-specific UUIDs user1UUID := uuid.NewSHA1(appNamespace, []byte("user1@example.com")) user2UUID := uuid.NewSHA1(appNamespace, []byte("user2@example.com")) // Same user always gets same UUID user1UUID2 := uuid.NewSHA1(appNamespace, []byte("user1@example.com")) // user1UUID == user1UUID2 (deterministic) ``` -------------------------------- ### Migrate from v4 to v7 Source: https://github.com/google/uuid/blob/master/_autodocs/version-comparison.md Shows how to switch from generating Version 4 UUIDs to Version 7. New generations will be v7, while existing v4 UUIDs remain unchanged. Version 7 offers timestamp information and sortability. ```go // Just switch on new generation // Old v4 UUIDs remain; new ones are v7 // Both sortable, v7 provides timestamp // Old code u := uuid.New() // v4 // New code u, _ := uuid.New7() // v7 ``` -------------------------------- ### Create and Use Version 7 UUIDs Source: https://github.com/google/uuid/blob/master/_autodocs/version-comparison.md Shows how to create Version 7 UUIDs with the current Unix timestamp, extract the timestamp, and use a randomness pool for high-volume generation. UUIDs are naturally sorted by time. ```go // Current Unix timestamp u, _ := uuid.NewV7() // Extract timestamp t := u.Time() sec, nsec := t.UnixTime() created := time.Unix(sec, nsec) // With randomness pool (recommended) uuid.EnableRandPool() for i := 0; i < 1000000; i++ { u, _ := uuid.NewV7() } // Naturally sorted by time u1, _ := uuid.NewV7() time.Sleep(1 * time.Millisecond) u2, _ := uuid.NewV7() // u1 < u2 (guaranteed by timestamp) // Custom reader u, _ := uuid.NewV7FromReader(customRandSource) ``` -------------------------------- ### Create and Use Version 6 UUIDs Source: https://github.com/google/uuid/blob/master/_autodocs/version-comparison.md Demonstrates creating Version 6 UUIDs using the current time or a custom timestamp, and extracting the timestamp. UUIDs are naturally sortable. ```go // Current time u, _ := uuid.NewV6() // Custom time t := time.Now().Add(-24 * time.Hour) u, _ := uuid.NewV6WithTime(&t) // Extract time t := u.Time() sec, nsec := t.UnixTime() // Sortable u1, _ := uuid.NewV6() u2, _ := uuid.NewV6() if u1 < u2 { fmt.Println("u1 was created before u2") } ``` -------------------------------- ### Handling Random Number Generator Panics Source: https://github.com/google/uuid/blob/master/_autodocs/errors.md Demonstrates how to use a custom reader for error handling with random UUID generation, as the default generator panics on failure. ```go // Panics if rander fails uuid, err := uuid.NewRandom() // Use custom reader if you need error handling uuid, err := uuid.NewRandomFromReader(myReader) if err != nil { // Handle read error } ``` -------------------------------- ### Import UUID Package Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Import the uuid package into your Go program. ```go import "github.com/google/uuid" ``` -------------------------------- ### Create MD5 Hash-Based UUIDs (v3) Source: https://github.com/google/uuid/blob/master/_autodocs/version-comparison.md Generates deterministic UUIDs using the MD5 hash algorithm based on a namespace and input data. Useful for legacy systems or when compatibility with existing MD5-based UUID schemes is required. ```go // Same inputs always produce same UUID namespace := uuid.NameSpaceDNS data := []byte("example.com") u1 := uuid.NewMD5(namespace, data) u2 := uuid.NewMD5(namespace, data) // u1 == u2 (always, deterministic) // Use with different namespaces u := uuid.NewMD5(uuid.NameSpaceURL, []byte("https://example.com/api")) ``` -------------------------------- ### Version.String Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/utilities.md Returns the string representation of a Version. Returns a formatted string: `VERSION_` for valid versions, `BAD_VERSION_` for invalid values. ```APIDOC ## Version.String ### Description Returns the string representation of a Version. ### Signature ```go func (v Version) String() string ``` ### Return Type `string` Returns a formatted string: `VERSION_` for valid versions, `BAD_VERSION_` for invalid values. ### Examples ```go v := uuid.Version(4) fmt.Println(v.String()) // "VERSION_4" v = uuid.Version(99) fmt.Println(v.String()) // "BAD_VERSION_99" ``` ``` -------------------------------- ### Parse Different UUID String Formats Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Demonstrates parsing UUIDs from various string formats including standard, URN, hex, and bracketed representations. All provided formats parse to the same UUID value. ```go // All of these parse to the same UUID u1, _ := uuid.Parse("550e8400-e29b-41d4-a716-446655440000") // Standard u2, _ := uuid.Parse("urn:uuid:550e8400-e29b-41d4-a716-446655440000") // URN u3, _ := uuid.Parse("550e8400e29b41d4a716446655440000") // Hex u4, _ := uuid.Parse("{550e8400-e29b-41d4-a716-446655440000}") // Bracketed // All equal if u1 == u2 && u2 == u3 && u3 == u4 { fmt.Println("All same") } ``` -------------------------------- ### UUID Generation Performance Baseline Source: https://github.com/google/uuid/blob/master/_autodocs/version-comparison.md Compares UUID generation throughput with and without the randomness pool enabled. The baseline shows performance without the pool, demonstrating the significant improvement when the pool is active. ```go // Baseline (no pool) for i := 0; i < 100000; i++ { u := uuid.Must(uuid.NewRandom()) // 5M/sec } ``` ```go // With pool (10x improvement) uuid.EnableRandPool() for i := 0; i < 100000; i++ { u := uuid.Must(uuid.NewRandom()) // 50M/sec } ``` -------------------------------- ### Benchmark UUID Generation Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Benchmarks the performance of generating new UUIDs. Run with `go test -bench=. -benchmem`. ```go import "testing" func BenchmarkUUIDGeneration(b *testing.B) { for i := 0; i < b.N; i++ { uuid.New() } } ``` -------------------------------- ### Well-Known Namespaces for Deterministic UUIDs Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Utilize predefined namespaces (DNS, URL, OID, X500) for generating deterministic UUIDs based on names or data. This ensures the same input always produces the same UUID. ```go uuid.NameSpaceDNS // 6ba7b810-9dad-11d1-80b4-00c04fd430c8 uuid.NameSpaceURL // 6ba7b811-9dad-11d1-80b4-00c04fd430c8 uuid.NameSpaceOID // 6ba7b812-9dad-11d1-80b4-00c04fd430c8 uuid.NameSpaceX500 // 6ba7b814-9dad-11d1-80b4-00c04fd430c8 // Usage u := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com")) u := uuid.NewSHA1(uuid.NameSpaceURL, []byte("https://example.com")) ``` -------------------------------- ### Benchmark UUID Parsing Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Benchmarks the performance of parsing UUID strings. Run with `go test -bench=. -benchmem`. ```go import "testing" func BenchmarkUUIDParsing(b *testing.B) { s := "550e8400-e29b-41d4-a716-446655440000" b.ResetTimer() for i := 0; i < b.N; i++ { uuid.Parse(s) } } // Run: go test -bench=. -benchmem ``` -------------------------------- ### Enable Randomness Pool for High-Volume Generation Source: https://github.com/google/uuid/blob/master/_autodocs/README.md Enable the randomness pool during initialization for significantly faster UUID generation in high-volume scenarios. This offers a trade-off of a small security reduction for improved throughput. ```go func init() { uuid.EnableRandPool() // Must call before concurrent access } // Later, UUID generation is faster for i := 0; i < 1000000; i++ { u := uuid.Must(uuid.NewRandom()) } ``` -------------------------------- ### Slice Operations: Create, Convert, Sort, and Check Contains Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Perform common operations on slices of UUIDs, including creating and appending, converting to strings, sorting using `uuid.Compare`, and checking for the existence of a specific UUID. ```go // Create slice of UUIDs ids := make([]uuid.UUID, 0, 10) for i := 0; i < 10; i++ { ids = append(ids, uuid.New()) } // Convert to strings strs := uuid.UUIDs(ids).Strings() // Sort UUIDs sort.Slice(ids, func(i, j int) bool { return uuid.Compare(ids[i], ids[j]) < 0 }) // Check if contains func contains(slice []uuid.UUID, id uuid.UUID) bool { for _, u := range slice { if u == id { return true } } return false } ``` -------------------------------- ### Nil and Max UUID Constants Source: https://github.com/google/uuid/blob/master/_autodocs/types.md Provides the zero UUID (Nil) and the maximum possible UUID (Max). ```go var Nil UUID // zero UUID: 00000000-0000-0000-0000-000000000000 var Max UUID // maximum UUID: ffffffff-ffff-ffff-ffff-ffffffffffff ``` -------------------------------- ### Catching ErrInvalidUUIDFormat Source: https://github.com/google/uuid/blob/master/_autodocs/errors.md Demonstrates how to check if an error is specifically ErrInvalidUUIDFormat. ```go if err == ErrInvalidUUIDFormat { // Handle invalid format } ``` -------------------------------- ### Generate Deterministic UUID (Version 5) Source: https://github.com/google/uuid/blob/master/_autodocs/README.md Creates a deterministic Version 5 UUID using SHA1 hashing based on a namespace and input data. ```Go u := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com")) ``` -------------------------------- ### Catching ErrInvalidURNPrefix Source: https://github.com/google/uuid/blob/master/_autodocs/errors.md Demonstrates how to catch errors related to an invalid URN prefix using errors.Is or by type assertion to access the specific prefix. ```go if errors.Is(err, ErrInvalidURNPrefix) { // Handle invalid URN prefix } // Or to access the prefix: if urnErr, ok := err.(URNPrefixError); ok { fmt.Printf("invalid prefix: %v\n", urnErr) } ``` -------------------------------- ### Compare and Sort UUIDs Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Compare UUIDs directly or lexicographically using uuid.Compare. Sorting a slice of UUIDs is demonstrated using sort.Slice. ```go u1 := uuid.New() u2 := uuid.New() // Direct comparison if u1 == u2 { fmt.Println("Same UUID") } // Lexicographic comparison cmp := uuid.Compare(u1, u2) if cmp < 0 { fmt.Println("u1 < u2") } else if cmp > 0 { fmt.Println("u1 > u2") } // Sorting slice графии := []uuid.UUID{u3, u1, u2} sort.Slice(uuids, func(i, j int) bool { return uuid.Compare(uuids[i], uuids[j]) < 0 }) // Convert slice to strings strs := uuid.UUIDs(uuids).Strings() ``` -------------------------------- ### Clock Management Methods Source: https://github.com/google/uuid/blob/master/_autodocs/api-index.md Methods for retrieving and setting the current time and clock sequence. ```APIDOC ## Clock Management ### Description Provides access to and control over the system's time and clock sequence for time-based UUIDs. ### Methods - `GetTime()`: Retrieves the current system time and clock sequence. - `ClockSequence()`: Gets the current clock sequence value. - `SetClockSequence(cs int)`: Sets a custom clock sequence value. ``` -------------------------------- ### Create DCE Security UUID (Version 2) Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/hash-and-dce.md Use NewDCESecurity to create a Version 2 UUID by providing a domain (Person, Group, Org) and a domain-specific ID. This function is time-based and can return the same token for up to 7 minutes for identical inputs. ```go import ( "github.com/google/uuid" "log" "fmt" ) // Generate UUID for user (Person domain) userId := uint32(501) u, err := uuid.NewDCESecurity(uuid.Person, userId) if err != nil { log.Fatal(err) } fmt.Println(u) // Generate for group groupId := uint32(100) u, err = uuid.NewDCESecurity(uuid.Group, groupId) // Organization domain orgId := uint32(1) u, err = uuid.NewDCESecurity(uuid.Org, orgId) // Extract domain and ID retrievedDomain := u.Domain() retrievedId := u.ID() fmt.Printf("Retrieved Domain: %s, ID: %d\n", retrievedDomain, retrievedId) ``` -------------------------------- ### NewV6 (Version 6 - Time + Node, Sortable) Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/uuid-generation.md Creates a Version 6 UUID, which is a field-compatible reordering of Version 1 with improved database locality. It returns a UUID and an error if the current time cannot be determined. ```APIDOC ## NewV6 (Version 6 - Time + Node, Sortable) ### Description Creates a Version 6 UUID, which is a field-compatible reordering of Version 1 with improved database locality. ### Method ```go func NewV6() (UUID, error) ``` ### Return Type `(UUID, error)` Returns a Version 6 UUID, or an error if the current time cannot be determined. ### Behavior - Time fields are reordered for lexicographic sorting (better for databases) - Auto-sets NodeID if not already set - Auto-sets clock sequence if not already set - If NodeID cannot be set, a random NodeID is generated ### Examples ```go id, err := uuid.NewV6() if err != nil { log.Fatal(err) } fmt.Println(id) // Lexicographically sortable ids := []uuid.UUID{ uuid.Must(uuid.NewV6()), uuid.Must(uuid.NewV6()), uuid.Must(uuid.NewV6()), } // Slice maintains time order without custom comparator sort.Slice(ids, func(i, j int) bool { return uuid.Compare(ids[i], ids[j]) < 0 }) ``` ``` -------------------------------- ### Generate New Random UUID as String (Version 4) Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/uuid-generation.md Use `uuid.NewString()` to generate a new random UUID directly as a string. This is a convenient shortcut for `uuid.New().String()` and is useful for direct integration with APIs or string-based storage. ```go import "fmt" import "github.com/google/uuid" id := uuid.NewString() fmt.Println(id) // e.g., "550e8400-e29b-41d4-a716-446655440000" // Direct use in APIs response := map[string]interface{}{ "id": uuid.NewString(), } ``` -------------------------------- ### Convert UUID Slice to Strings and Sort Source: https://github.com/google/uuid/blob/master/_autodocs/README.md Convert a slice of UUIDs to a slice of their string representations and demonstrate lexicographical sorting of UUIDs using the Compare function. ```go ids := []uuid.UUID{uuid.New(), uuid.New(), uuid.New()} // Convert to strings strs := uuid.UUIDs(ids).Strings() // Sort sort.Slice(ids, func(i, j int) bool { return uuid.Compare(ids[i], ids[j]) < 0 }) ``` -------------------------------- ### MustParse UUID, panics on error Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/parsing-and-conversion.md Use MustParse for safe global variable initialization. It panics if the input string is not a valid UUID format. ```go var DNSNamespace = uuid.MustParse("6ba7b810-9dad-11d1-80b4-00c04fd430c8") ``` ```go id := uuid.MustParse("invalid") // Panics: uuid: Parse(invalid): invalid UUID format ``` -------------------------------- ### Create DCE Person UUID (Version 2) Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/hash-and-dce.md Use NewDCEPerson to create a Version 2 UUID for the current user's UID. This function is equivalent to NewDCESecurity(Person, os.Getuid()) and is only available on POSIX systems. ```go import ( "github.com/google/uuid" "log" "fmt" ) u, err := uuid.NewDCEPerson() if err != nil { log.Fatal(err) } fmt.Println(u) // Extract the UID uid := u.ID() fmt.Printf("Current UID: %d\n", uid) ``` -------------------------------- ### Lexicographically Compare UUIDs Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/utilities.md Compare two UUIDs to determine their order. This is essential for sorting slices of UUIDs. ```go u1 := uuid.Must(uuid.NewV6()) u2 := uuid.Must(uuid.NewV6()) cmp := uuid.Compare(u1, u2) if cmp < 0 { fmt.Println("u1 < u2") } else if cmp > 0 { fmt.Println("u1 > u2") } else { fmt.Println("u1 == u2") } // Use with sorting uuids := []uuid.UUID{u3, u1, u2} sort.Slice(uuids, func(i, j int) bool { return uuid.Compare(uuids[i], uuids[j]) < 0 }) ``` -------------------------------- ### NewV7FromReader Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/uuid-generation.md Creates a Version 7 UUID using a custom random source provided as an io.Reader. This is useful for scenarios requiring specific random data generation, such as testing with deterministic sources. ```APIDOC ## NewV7FromReader ### Description Creates a Version 7 UUID using a custom random source. The provided `io.Reader` must supply 16 bytes of random data. ### Signature ```go func NewV7FromReader(r io.Reader) (UUID, error) ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | r | io.Reader | Yes | — | Source of random bytes (must provide 16 bytes) | ### Response #### Success Response - Returns a Version 7 UUID generated with the provided random source. #### Error Response - Returns an error if the read operation fails. ### Examples ```go import ( "crypto/rand" ) u, err := uuid.NewV7FromReader(rand.Reader) // Testing with deterministic source testBytes := make([]byte, 16) u, err := uuid.NewV7FromReader(bytes.NewReader(testBytes)) ``` ``` -------------------------------- ### SQL Scanning for Optional UUIDs (NullUUID.Scan) Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/serialization-and-database.md Implements `sql.Scanner` for `NullUUID` to handle nullable UUID fields in database queries. Sets `Valid` to false if the database value is nil. ```go type User struct { ID uuid.UUID SecondID uuid.NullUUID // Optional UUID } row := db.QueryRow("SELECT id, second_id FROM users WHERE id = ?", userId) err := row.Scan(&user.ID, &user.SecondID) if err != nil { log.Fatal(err) } if user.SecondID.Valid { fmt.Println("Secondary ID:", user.SecondID.UUID) } else { fmt.Println("No secondary ID") } ``` -------------------------------- ### Create Version 5 (SHA1) UUIDs Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/hash-and-dce.md Use NewSHA1 to generate a Version 5 UUID from a namespace and data using SHA1 hashing. This is the recommended method for new implementations according to RFC 9562. The generated UUIDs are deterministic. ```go import "fmt" import "github.com/google/uuid" // UUID from DNS name (RFC recommended) u := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com")) fmt.Println(u) // e.g., "886313e1-3b8a-5372-9b90-0c9aee199e5d" // UUID from user email (custom namespace) userNamespace := uuid.NameSpaceURL userEmail := []byte("user@example.com") u := uuid.NewSHA1(userNamespace, userEmail) // Deterministic across program runs u1 := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com")) u2 := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com")) // u1 == u2 // Create custom namespace UUID customNamespace := uuid.NewSHA1(uuid.NameSpaceURL, []byte("https://myapp.example.com")) // Use custom namespace for app-specific UUIDs appUUID := uuid.NewSHA1(customNamespace, []byte("user123")) ``` -------------------------------- ### Performance Tuning for UUID Generation Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Enable the randomness pool for high-volume UUID generation, significantly improving throughput for Version 4 and 7. A custom random source can also be set. ```go // For high-volume generation, enable randomness pool uuid.EnableRandPool() defer uuid.DisableRandPool() // Pool significantly improves Version 4 and 7 throughput for i := 0; i < 1000000; i++ { u, _ := uuid.NewV7() // Much faster with pool } // Custom random source f, _ := os.Open("/dev/urandom") uuid.SetRand(f) ``` -------------------------------- ### Create Version 3 (MD5) UUIDs Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/hash-and-dce.md Use NewMD5 to generate a Version 3 UUID from a namespace and data using MD5 hashing. This is suitable for legacy systems; prefer Version 5 for new implementations. The same inputs will always produce the same UUID. ```go import "fmt" import "github.com/google/uuid" // UUID from DNS name u := uuid.NewMD5(uuid.NameSpaceDNS, []byte("example.com")) fmt.Println(u) // Deterministic output // UUID from URL u := uuid.NewMD5(uuid.NameSpaceURL, []byte("https://example.com/path")) // Multiple calls with same input produce same UUID u1 := uuid.NewMD5(uuid.NameSpaceDNS, []byte("example.com")) u2 := uuid.NewMD5(uuid.NameSpaceDNS, []byte("example.com")) // u1 == u2 (always) ``` -------------------------------- ### Time Methods Source: https://github.com/google/uuid/blob/master/_autodocs/api-index.md Methods available for the Time type, representing 100-nanosecond intervals. ```APIDOC ## Time Methods ### Description Provides conversion from Time to Unix time. ### Method - **UnixTime** `(t Time) UnixTime() (sec, nsec int64)` - Converts the Time value to seconds and nanoseconds since the Unix epoch. ``` -------------------------------- ### Generate a UUID (Version 4) Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Generate a random Version 4 UUID. Error handling is recommended for production code. ```go // Random (Version 4) - simplest u := uuid.New() fmt.Println(u) // e.g., "550e8400-e29b-41d4-a716-446655440000" // With error handling u, err := uuid.NewRandom() if err != nil { log.Fatal(err) } // String directly str := uuid.NewString() ``` -------------------------------- ### Use UUID as Map Key Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md UUIDs are comparable and can be used directly as keys in Go maps. ```go // UUID is comparable, works as map key userMap := make(map[uuid.UUID]string) id := uuid.New() userMap[id] = "Alice" if name, exists := userMap[id]; exists { fmt.Println(name) } ``` -------------------------------- ### Database Integration Methods Source: https://github.com/google/uuid/blob/master/_autodocs/api-index.md Methods for integrating UUIDs with SQL databases, supporting scanning and value conversion. ```APIDOC ## Database Integration ### Description Provides methods for seamless integration with SQL databases, implementing `sql.Scanner` and `sql.driver.Valuer` interfaces. ### Methods - `UUID.Scan(value interface{}) error`: Reads a UUID value from a database column. - `UUID.Value() (driver.Value, error)`: Writes a UUID value to a database column. - `NullUUID.Scan(value interface{}) error`: Reads a nullable UUID value from a database column. - `NullUUID.Value() (driver.Value, error)`: Writes a nullable UUID value to a database column. ``` -------------------------------- ### Domain Type Definition Source: https://github.com/google/uuid/blob/master/_autodocs/types.md Defines the Domain type as a byte, representing a Version 2 (DCE Security) domain. ```go type Domain byte ``` -------------------------------- ### Utility Functions Source: https://github.com/google/uuid/blob/master/_autodocs/DOCUMENTATION.md Utility functions for inspecting UUID properties, comparison, and slice manipulation. ```APIDOC ## Utility Functions ### UUID.Version() int **Description**: Returns the version number of the UUID. ### UUID.Variant() int **Description**: Returns the variant type of the UUID. ### Compare(u1, u2 UUID) int **Description**: Performs a lexicographical comparison between two UUIDs. ### UUIDs.Strings() []string **Description**: Converts a slice of UUIDs to a slice of strings. ### Nil UUID constant **Description**: Represents the nil UUID (all zeros). ### Max UUID constant **Description**: Represents the maximum possible UUID value. ### Go interface implementations **Description**: Implements standard Go interfaces such as Stringer, Marshaler, Comparable, etc. ``` -------------------------------- ### Version Type Definition Source: https://github.com/google/uuid/blob/master/_autodocs/types.md Defines the Version type as a byte, representing the version number of a UUID. ```go type Version byte ``` -------------------------------- ### NewV7 Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/uuid-generation.md Creates a Version 7 UUID based on the Unix epoch timestamp in milliseconds. This method is recommended for new implementations due to its time-ordered nature and inclusion of random bits for uniqueness. ```APIDOC ## NewV7 ### Description Creates a Version 7 UUID based on Unix epoch timestamp (milliseconds since Jan 1, 1970 UTC). This method is recommended for new implementations due to its time-ordered nature (48 bits) and inclusion of random bits for uniqueness. ### Signature ```go func NewV7() (UUID, error) ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Response #### Success Response - Returns a Version 7 UUID. #### Error Response - Returns an error if random data cannot be generated. ### Examples ```go id, err := uuid.NewV7() if err != nil { log.Fatal(err) } fmt.Println(id) // Recommended for new systems type Event struct { ID uuid.UUID `json:"id"` Timestamp int64 `json:"timestamp"` Data string `json:"data"` } ``` ``` -------------------------------- ### Configure UUID Random Number Generator Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/utilities.md Sets the random number generator for UUID generation. Can be nil to use the default crypto/rand.Reader, a custom reader like /dev/urandom, or a deterministic reader for testing. Panics if the reader fails during UUID generation. ```go import ( "crypto/rand" "github.com/google/uuid" ) // Use default uuid.SetRand(nil) // Custom source (not recommended for production) f, _ := os.Open("/dev/urandom") deferr f.Close() uuid.SetRand(f) // For testing with deterministic source testBytes := make([]byte, 16) uuid.SetRand(bytes.NewReader(testBytes)) u := uuid.Must(uuid.NewRandom()) ``` -------------------------------- ### Set Random Source and Node ID Source: https://github.com/google/uuid/blob/master/_autodocs/quick-reference.md Configure the random number generator and set a specific node ID or interface for UUID generation. Use `nil` for the default random source or auto-select the network interface. ```go // Set random source import "crypto/rand" uuid.SetRand(rand.Reader) // or nil for default // Node ID (for v1/v6 generation) uuid.SetNodeID([]byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55}) uuid.SetNodeInterface("eth0") // or "" for auto-select // Clock sequence (for v1/v6/v2) uuid.SetClockSequence(1234) // specific sequence uuid.SetClockSequence(-1) // random sequence // Check current settings nodeInterface := uuid.NodeInterface() nodeID := uuid.NodeID() seq := uuid.ClockSequence() ``` -------------------------------- ### Check for Nil UUID Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/utilities.md Compare a UUID against the predefined `uuid.Nil` constant. This is useful for identifying unset or zero values. ```go u := uuid.UUID{} if u == uuid.Nil { fmt.Println("UUID is nil") } // Compare to Nil if u != uuid.Nil { fmt.Println("UUID is set") } // Scan returns Nil on NULL in database var u uuid.UUID db.QueryRow("SELECT NULL").Scan(&u) if u == uuid.Nil { fmt.Println("NULL from database") } ``` -------------------------------- ### Check UUID Range with Nil and Max Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/utilities.md Use `uuid.Nil` and `uuid.Max` constants to define the valid range for UUIDs. This is helpful for database queries or validation. ```go // Range query in database rows, _ := db.Query( "SELECT * FROM ids WHERE uuid >= ? AND uuid <= ?", uuid.Nil, uuid.Max, ) // Check if UUID is valid u := uuid.New() if uuid.Compare(u, uuid.Nil) > 0 && uuid.Compare(u, uuid.Max) < 0 { fmt.Println("UUID is in valid range") } ``` -------------------------------- ### FromBytes Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/parsing-and-conversion.md Creates a UUID from a 16-byte slice. ```APIDOC ## FromBytes ### Description Creates a UUID from a 16-byte slice. ### Method `func FromBytes(b []byte) (UUID, error)` ### Parameters #### Path Parameters - **b** ([]byte) - Required - Exactly 16 bytes representing the UUID ### Return Type `(UUID, error)` Returns a UUID if the slice is exactly 16 bytes. Returns an error if the length is wrong. ### Examples ```go // From database binary data var bytes [16]byte copy(bytes[:], data) u, err := uuid.FromBytes(bytes[:]) // From network packet u, err := uuid.FromBytes(packetData[offset : offset+16]) if err != nil { log.Fatal("Invalid UUID data length") } ``` ``` -------------------------------- ### NewSHA1 Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/hash-and-dce.md Creates a Version 5 UUID from SHA1 hash of namespace and data. This is the recommended method for new implementations. ```APIDOC ## NewSHA1 ### Description Creates a Version 5 UUID using the SHA1 hash algorithm. This is the recommended method for new implementations due to SHA1's improved security over MD5. ### Method `NewSHA1(space UUID, data []byte) UUID` ### Parameters #### Path Parameters - **space** (UUID) - Required - Namespace UUID - **data** ([]byte) - Required - Data to hash ### Return Type `UUID` Returns a Version 5 (SHA1) UUID. Deterministic: same inputs always produce same output. ### Behavior - Equivalent to `NewHash(sha1.New(), space, data, 5)` - Uses SHA1 hash algorithm - Preferred over Version 3 (MD5) for new implementations - RFC 9562 recommends this for deriving UUIDs from names ### Common Namespaces - `NameSpaceDNS` — For DNS names - `NameSpaceURL` — For URLs - `NameSpaceOID` — For OIDs - `NameSpaceX500` — For X.500 names ### Examples ```go // UUID from DNS name (RFC recommended) u := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com")) fmt.Println(u) // e.g., "886313e1-3b8a-5372-9b90-0c9aee199e5d" // UUID from user email (custom namespace) userNamespace := uuid.NameSpaceURL userEmail := []byte("user@example.com") u := uuid.NewSHA1(userNamespace, userEmail) // Deterministic across program runs u1 := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com")) u2 := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com")) // u1 == u2 // Create custom namespace UUID customNamespace := uuid.NewSHA1(uuid.NameSpaceURL, []byte("https://myapp.example.com")) // Use custom namespace for app-specific UUIDs appUUID := uuid.NewSHA1(customNamespace, []byte("user123")) ``` ``` -------------------------------- ### JSON Marshalling for UUID (UUID.MarshalJSON) Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/serialization-and-database.md Implements `json.Marshaler` for `UUID`, returning the UUID as a quoted JSON string. ```go import "encoding/json" type User struct { ID uuid.UUID `json:"id"` Name string `json:"name"` } user := User{ ID: uuid.New(), Name: "Alice", } data, _ := json.Marshal(user) // JSON: {"id":"550e8400-e29b-41d4-a716-446655440000","name":"Alice"} ``` -------------------------------- ### Stringer (fmt.Stringer) Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/utilities.md The UUID type implements the `fmt.Stringer` interface, allowing it to be automatically formatted as a string by functions like `fmt.Print`, `fmt.Println`, and `fmt.Sprintf`. ```APIDOC ## Stringer (fmt.Stringer) ### Description The UUID type implements the `fmt.Stringer` interface, allowing it to be automatically formatted as a string by functions like `fmt.Print`, `fmt.Println`, and `fmt.Sprintf`. ### Signature ```go func (uuid UUID) String() string ``` ### Parameters None ### Response - Returns the string representation of the UUID. ### Request Example ```go u := uuid.New() fmt.Println(u) // Calls String() fmt.Printf("%v\n", u) // Calls String() ``` ### Response Example ```json { "example": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### String Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/parsing-and-conversion.md Returns the string representation of a UUID in standard notation (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx). ```APIDOC ## String ### Description Returns the string representation of a UUID in standard notation. ### Signature ```go func (uuid UUID) String() string ``` ### Parameters (This is a method on the UUID type, no explicit parameters) ### Return Type `string` Returns the UUID in standard format: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`, or an empty string if the UUID is invalid. ### Examples: ```go u := uuid.New() fmt.Println(u.String()) // Output: something like "550e8400-e29b-41d4-a716-446655440000" // Use in string formatting fmt.Printf("ID: %s\n", u) // Uses String() implicitly via Stringer interface // Database queries query := fmt.Sprintf("SELECT * FROM users WHERE id = '%s'", u) ``` ``` -------------------------------- ### JSON Marshalling and Unmarshalling UUIDs Source: https://github.com/google/uuid/blob/master/_autodocs/README.md Shows how to marshal a struct containing a UUID into JSON and unmarshal JSON data back into the struct. ```Go type User struct { ID uuid.UUID `json:"id"` Name string `json:"name"` } // Marshal data, _ := json.Marshal(user) // {"id":"550e8400-e29b-41d4-a716-446655440000","name":"Alice"} // Unmarshal var user User json.Unmarshal(data, &user) ``` -------------------------------- ### Utility Functions Source: https://github.com/google/uuid/blob/master/_autodocs/api-index.md Utility functions for comparing UUIDs, converting slices, and handling errors. ```APIDOC ## Utilities ### Description A collection of utility functions for common UUID operations. ### Functions - `Compare(a, b UUID)`: Compares two UUIDs and returns an integer indicating their order. - `UUIDs.Strings(uuids []UUID)`: Converts a slice of UUIDs to a slice of strings. - `Must(u UUID, err error)`: A wrapper that panics if an error occurs during UUID creation or operation. - `IsInvalidLengthError(err error)`: Checks if the given error is an `InvalidLengthError`. ``` -------------------------------- ### Version Methods Source: https://github.com/google/uuid/blob/master/_autodocs/api-index.md Methods available for the Version type, used to identify the UUID version. ```APIDOC ## Version Methods ### Description Provides a string representation for the UUID version. ### Method - **String** `(v Version) String() string` - Returns the string representation of the UUID version. ``` -------------------------------- ### Compare Source: https://github.com/google/uuid/blob/master/_autodocs/api-reference/utilities.md Compares two UUIDs lexicographically. Returns 0 if a == b, -1 if a < b, and +1 if a > b. ```APIDOC ## Compare ### Description Compares two UUIDs lexicographically. ### Signature ```go func Compare(a, b UUID) int ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | a | UUID | Yes | — | First UUID | | b | UUID | Yes | — | Second UUID | ### Return Type `int` Returns: - 0 if a == b - -1 if a < b - +1 if a > b ### Examples ```go u1 := uuid.Must(uuid.NewV6()) u2 := uuid.Must(uuid.NewV6()) cmp := uuid.Compare(u1, u2) if cmp < 0 { fmt.Println("u1 < u2") } else if cmp > 0 { fmt.Println("u1 > u2") } else { fmt.Println("u1 == u2") } // Use with sorting uuids := []uuid.UUID{u3, u1, u2} sort.Slice(uuids, func(i, j int) bool { return uuid.Compare(uuids[i], uuids[j]) < 0 }) ``` ```