gofrs/uuid

repository·master·Indexed 23 days ago

https://github.com/gofrs/uuid

A pure Go implementation of Universally Unique Identifiers (UUID) compliant with RFC-9562. It supports generating and parsing UUID versions 1, 3, 4, 5, 6, 7, and 8, including k-sortable IDs. The library provides utilities for SQL database integration via driver.Valuer and sql.Scanner, JSON marshaling for NullUUID, and timestamp extraction for V1, V6, and V7 UUIDs. Requires Go 1.25 or later; version v2.0.0 or later is recommended.

Tokens
3.5K
Snippets
4
Records
28
Agent score
81%

What's inside gofrs-uuid

  1. Supported UUID versions

    master

    The package implements the following UUID versions as defined in RFC-9562:

    • Version 1: Based on timestamp and MAC address.
    • Version 3: Based on MD5 hashing of a named value.
    • Version 4: Based on random numbers.
    • Version 5: Based on SHA-1 hashing of a named value.
    • Version 6: A k-sortable ID based on timestamp, field-compatible with v1.
    • Version 7: A k-sortable ID based on timestamp.
    • Version 8: For custom UUID implementations.
  2. Install and use gofrs/uuid/v5

    master

    The gofrs/uuid package provides a pure Go implementation of Universally Unique Identifiers (UUID) as defined in RFC-9562. It supports creating and parsing various UUID versions including v1, v3, v4, v5, v6, v7, and v8.

    Requirements

    • Go 1.25 or later

    Use version v2.0.0 or later. Versions prior to v2.0.0 are from the original fork and may contain known deficiencies.

  3. How UUID V7 monotonic counters work

    master

    UUID V7 supports single-node batch generation (multiple UUIDs within the same millisecond) using a 12-bit monotonic counter in the rand_a field.

    Key Behaviors:

    • Strict Ordering: UUIDs returned by a single generator are strictly increasing, even if the system clock moves backwards.
    • Counter Capacity: The counter is reseeded with 11 random bits at the start of every millisecond tick, providing at least 2048 increments per tick.
    • Overflow Strategy: If you generate UUIDs faster than the counter can increment (roughly 2 million per second), the generator increments the embedded timestamp ahead of the actual time to preserve ordering, trading off timestamp accuracy for sortability.
  4. Generate and parse UUIDs

    master

    You can generate new UUIDs using version-specific functions (like NewV4()) or parse existing UUIDs from strings using FromString().

    If you are initializing package-level variables and want to avoid error handling at runtime, use the Must() helper which panics if the UUID generation fails.

    package main
    
    import (
    	"log"
    
    	"github.com/gofrs/uuid/v5"
    )
    
    // Create a Version 4 UUID, panicking on error.
    // Use this form to initialize package-level variables.
    var u1 = uuid.Must(uuid.NewV4())
    
    func main() {
    	// Create a Version 4 UUID.
    	u2, err := uuid.NewV4()
    	if err != nil {
    		log.Fatalf("failed to generate UUID: %v", err)
    	}
    	log.Printf("generated Version 4 UUID %v", u2)
    
    	// Parse a UUID from a string.
    	s := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
    	u3, err := uuid.FromString(s)
    	if err != nil {
    		log.Fatalf("failed to parse UUID %q: %v", s, err)
    	}
    	log.Printf("successfully parsed UUID %v", u3)
    }
  5. Create a custom UUID Generator with options

    master

    While uuid.NewV1() and other package-level functions use the DefaultGenerator, you can create a highly customized generator using NewGenWithOptions. This is useful for testing (mocking time/randomness) or for security (obfuscating MAC addresses).

    Configuration Options:

    • WithHWAddrFunc(hwaf HWAddrFunc): Provide a custom function to supply MAC addresses. This is recommended if you want to avoid exposing the physical hardware address of your machine in V1/V6 UUIDs.
    • WithEpochFunc(epochf EpochFunc): Provide a custom function for the current time (e.g., for testing).
    • WithRandomReader(reader io.Reader): Provide a custom source of randomness.
  6. Extract timestamps from V1, V6, and V7 UUIDs

    master

    Certain UUID versions embed timestamp data. The package provides specific functions to extract this data into a Timestamp type, which represents 100-nanosecond intervals since 15 October 1582.

    • TimestampFromV1(u UUID): Extracts the timestamp from a Version 1 UUID. Returns an error if the UUID is not version 1.
    • TimestampFromV6(u UUID): Extracts the timestamp from a Version 6 UUID. Returns an error if the UUID is not version 6.
    • TimestampFromV7(u UUID): Extracts the timestamp from a Version 7 UUID. Returns an error if the UUID is not version 7.

    Once you have a Timestamp, you can convert it to a standard Go time.Time using the .Time() method.

  7. Generate standard UUID versions (V1, V3, V4, V5, V6, V7, V8)

    master

    The package provides several ways to generate UUIDs depending on your requirements for randomness, sortability, or determinism. You can use the package-level functions for quick access to the DefaultGenerator, or use a custom Generator instance for more control.

    Available UUID Versions:

    • V1: Based on current timestamp and MAC address.
    • V3: Deterministic (MD5 hash of namespace and name).
    • V4: Randomly generated.
    • V5: Deterministic (SHA-1 hash of namespace and name).
    • V6: K-sortable (timestamp + pseudorandom data).
    • V7: K-sortable (millisecond-precision UNIX epoch + pseudorandom data). Supports monotonic counters for batch generation.
    • V8: Custom UUID based on user-provided data (RFC 9562).
  8. Format UUIDs as strings or hex

    master

    The UUID type implements fmt.Formatter, allowing for various string representations using standard Go formatting verbs:

    • %s, %v: Canonical RFC-9562 string (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
    • %x: Hexadecimal digits (lowercase).
    • %X: Hexadecimal digits (uppercase).
    • %S: Canonical RFC-9562 string with uppercase hex digits.
    • %q: Quoted canonical string ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
    • %#v: Go syntax representation (a 16-byte array initializer).
  9. Marshal and Unmarshal NullUUID in JSON

    master

    The NullUUID type provides custom JSON marshaling to handle nullability in API responses and requests:

    • Marshaling: If Valid is false, it encodes to the JSON literal null. If Valid is true, it encodes the UUID as a quoted string.
    • Unmarshaling:
      • If the input is the JSON literal null, it sets Valid to false and UUID to Nil.
      • If the input is a quoted string, it unmarshals the text into the UUID. The Valid field is set to true if unmarshaling succeeds, and false otherwise.
  10. Generate custom V8 UUIDs

    master

    UUID V8 allows you to embed custom data into the UUID structure as specified in RFC 9562. The generator requires three byte slices of exact lengths:

    • customA: Exactly 6 bytes (48 bits).
    • customB: Exactly 2 bytes (16 bits, but only the lower 12 bits are used).
    • customC: Exactly 8 bytes (64 bits, but only the lower 62 bits are used).

    If any slice does not meet these length requirements, the function returns ErrV8FieldLength.

  11. Set UUID version and variant

    master

    You can manually modify the version or variant bits of a UUID instance using pointer receivers:

    • SetVersion(v byte): Sets the version bits.
    • SetVariant(v byte): Sets the variant bits (supports VariantNCS, VariantRFC9562, VariantMicrosoft, and VariantFuture).
  12. Create a UUID from a string

    master

    Use FromString(text string) to parse a UUID from a string representation. This function supports multiple formats including canonical (with dashes), hash-like (no dashes), braced formats, and URN prefixes. If parsing fails, it returns an error.

    If you prefer to receive uuid.Nil instead of an error when parsing fails, use FromStringOrNil(input string).