### Install TypeID Go Library Source: https://github.com/jetify-com/typeid-go/blob/main/README.md Add the TypeID Go library as a dependency to your project using the go get command. ```bash go get go.jetify.com/typeid/v2 ``` -------------------------------- ### Convert UUID to TypeID Source: https://context7.com/jetify-com/typeid-go/llms.txt Creates a TypeID from an existing UUID string in hex format. Useful for migrating from UUIDs or converting between formats. Supports creating TypeIDs with or without a prefix. Includes a round-trip verification example. ```go package main import ( "fmt" "log" "go.jetify.com/typeid/v2" ) func main() { // Convert existing UUID to TypeID existingUUID := "550e8400-e29b-41d4-a716-446655440000" customerID, err := typeid.FromUUID("customer", existingUUID) if err != nil { log.Fatal(err) } fmt.Println(customerID.String()) // Output: customer_2n1t201rmv87aae5j4csam8000 fmt.Println(customerID.UUID()) // Output: 550e8400-e29b-41d4-a716-446655440000 // Round-trip verification recoveredUUID := customerID.UUID() fmt.Println(recoveredUUID == existingUUID) // Output: true // Create bare TypeID from UUID bareID, err := typeid.FromUUID("", existingUUID) if err != nil { log.Fatal(err) } fmt.Println(bareID.String()) // Output: 2n1t201rmv87aae5j4csam8000 } ``` -------------------------------- ### Generate TypeID Source: https://context7.com/jetify-com/typeid-go/llms.txt Creates a new TypeID with the given type prefix and a random UUIDv7 suffix. The prefix must contain only lowercase letters (a-z) and underscores, cannot start or end with underscore, and must be 63 characters or fewer. Pass an empty string for no prefix. ```APIDOC ## Generate TypeID ### Description Creates a new TypeID with the given type prefix and a random UUIDv7 suffix. ### Method `typeid.Generate(prefix string) (TypeID, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "log" "go.jetify.com/typeid/v2" ) func main() { // Generate a TypeID for a user entity userID, err := typeid.Generate("user") if err != nil { log.Fatal(err) } fmt.Println(userID.String()) // Output: user_01h455vb4pex5vsknk084sn02q // Generate without a prefix (bare TypeID) bareID, err := typeid.Generate("") if err != nil { log.Fatal(err) } fmt.Println(bareID.String()) // Output: 01h455vb4pex5vsknk084sn02q // Extract components fmt.Println(userID.Prefix()) // Output: user fmt.Println(userID.Suffix()) // Output: 01h455vb4pex5vsknk084sn02q fmt.Println(userID.UUID()) // Output: 018e5f71-6f04-7c5c-8123-456789abcdef } ``` ### Response #### Success Response (200) - **TypeID** (typeid.TypeID) - The generated TypeID. - **error** (error) - An error if the prefix is invalid. #### Response Example ``` user_01h455vb4pex5vsknk084sn02q ``` ``` -------------------------------- ### Integrate TypeID with SQL Databases in Go Source: https://context7.com/jetify-com/typeid-go/llms.txt Demonstrates how to insert and query TypeIDs using `sql.Scanner` and `sql.Valuer` interfaces. Handles nullable TypeID columns with `sql.Null[TypeID]`. ```go package main import ( "database/sql" "fmt" "log" "go.jetify.com/typeid/v2" _ "github.com/lib/pq" // PostgreSQL driver ) func main() { db, err := sql.Open("postgres", "postgres://localhost/myapp?sslmode=disable") if err != nil { log.Fatal(err) } defer db.Close() // Insert with TypeID userID := typeid.MustGenerate("user") _, err = db.Exec( "INSERT INTO users (id, name, email) VALUES ($1, $2, $3)", userID, "Alice", "alice@example.com", ) if err != nil { log.Fatal(err) } // Query and scan TypeID var retrievedID typeid.TypeID var name, email string err = db.QueryRow( "SELECT id, name, email FROM users WHERE id = $1", userID, ).Scan(&retrievedID, &name, &email) if err != nil { log.Fatal(err) } fmt.Printf("User: %s (%s) - %s\n", name, retrievedID, email) // Output: User: Alice (user_01h455vb4pex5vsknk084sn02q) - alice@example.com // Handle nullable TypeID columns with sql.Null[TypeID] var managerID sql.Null[typeid.TypeID] err = db.QueryRow( "SELECT manager_id FROM users WHERE id = $1", userID, ).Scan(&managerID) if err != nil { log.Fatal(err) } if managerID.Valid { fmt.Println("Manager:", managerID.V.String()) } else { fmt.Println("No manager assigned") } } ``` -------------------------------- ### Generate and Parse TypeIDs in Go Source: https://github.com/jetify-com/typeid-go/blob/main/README.md Demonstrates generating new TypeIDs with and without prefixes, handling errors during generation, parsing existing TypeIDs, and converting from UUIDs. ```go import ( "fmt" "log" "go.jetify.com/typeid/v2" ) func example() { // Generate a new TypeID with a prefix (panics on invalid prefix) tid := typeid.MustGenerate("user") fmt.Println(tid) // Generate a new TypeID without a prefix tid = typeid.MustGenerate("") fmt.Println(tid) // Generate with error handling tid, err := typeid.Generate("user") if err != nil { log.Fatal(err) } // Parse an existing TypeID tid, _ = typeid.Parse("user_00041061050r3gg28a1c60t3gf") fmt.Println(tid) // Convert from UUID tid, _ = typeid.FromUUID("user", "018e5f71-6f04-7c5c-8123-456789abcdef") fmt.Println(tid) } ``` -------------------------------- ### Generate TypeID with Prefix and Suffix Source: https://context7.com/jetify-com/typeid-go/llms.txt Creates a new TypeID with a given type prefix and a random UUIDv7 suffix. The prefix must adhere to specific naming conventions. Demonstrates extracting components like prefix, suffix, and UUID. ```go package main import ( "fmt" "log" "go.jetify.com/typeid/v2" ) func main() { // Generate a TypeID for a user entity userID, err := typeid.Generate("user") if err != nil { log.Fatal(err) } fmt.Println(userID.String()) // Output: user_01h455vb4pex5vsknk084sn02q // Generate without a prefix (bare TypeID) bareID, err := typeid.Generate("") if err != nil { log.Fatal(err) } fmt.Println(bareID.String()) // Output: 01h455vb4pex5vsknk084sn02q // Extract components fmt.Println(userID.Prefix()) // Output: user fmt.Println(userID.Suffix()) // Output: 01h455vb4pex5vsknk084sn02q fmt.Println(userID.UUID()) // Output: 018e5f71-6f04-7c5c-8123-456789abcdef } ``` -------------------------------- ### Extract TypeID Components and Check State Source: https://context7.com/jetify-com/typeid-go/llms.txt Utilize TypeID methods to extract its prefix, suffix, UUID string, and raw bytes. Check for the zero value of a TypeID using `IsZero()` and if it contains a non-zero suffix with `HasSuffix()`. ```go package main import ( "fmt" "go.jetify.com/typeid/v2" ) func main() { tid := typeid.MustGenerate("invoice") // Extract all components fmt.Println("Full ID:", tid.String()) // Output: invoice_01h455vb4pex5vsknk084sn02q fmt.Println("Prefix:", tid.Prefix()) // Output: invoice fmt.Println("Suffix:", tid.Suffix()) // Output: 01h455vb4pex5vsknk084sn02q fmt.Println("UUID:", tid.UUID()) // Output: 018e5f71-6f04-7c5c-8123-456789abcdef fmt.Printf("Bytes: %x\n", tid.Bytes()) // Output: Bytes: 018e5f716f047c5c8123456789abcdef // Check zero state var zeroTid typeid.TypeID fmt.Println("IsZero:", zeroTid.IsZero()) // Output: true fmt.Println("HasSuffix:", zeroTid.HasSuffix()) // Output: false fmt.Println("Zero string:", zeroTid.String()) // Output: 00000000000000000000000000 // Non-zero TypeID fmt.Println("IsZero:", tid.IsZero()) // Output: false fmt.Println("HasSuffix:", tid.HasSuffix()) // Output: true } ``` -------------------------------- ### Handle TypeID Validation Errors in Go Source: https://context7.com/jetify-com/typeid-go/llms.txt Shows how to check for TypeID validation errors using `errors.Is(err, typeid.ErrValidation)`. Covers invalid prefixes, lengths, suffixes, and UUID formats. ```go package main import ( "errors" "fmt" "go.jetify.com/typeid/v2" ) func main() { // Invalid prefix: uppercase letters _, err := typeid.Generate("User") if errors.Is(err, typeid.ErrValidation) { fmt.Println("Prefix error:", err) // Output: Prefix error: typeid: prefix must contain only [a-z_], found 'U' in "User" } // Invalid prefix: too long (max 63 chars) longPrefix := "this_is_a_very_long_prefix_that_exceeds_the_maximum_allowed_length_limit" _, err = typeid.Generate(longPrefix) if errors.Is(err, typeid.ErrValidation) { fmt.Println("Length error:", err) // Output: Length error: typeid: prefix length must be <= 63, got 72 for "..." } // Invalid suffix during parsing _, err = typeid.Parse("user_invalid!suffix") if errors.Is(err, typeid.ErrValidation) { fmt.Println("Suffix error:", err) // Output: Suffix error: typeid: suffix length must be 26, got 15 } // Invalid UUID format _, err = typeid.FromUUID("user", "not-a-valid-uuid") if errors.Is(err, typeid.ErrValidation) { fmt.Println("UUID error:", err) // Output: UUID error: typeid: invalid UUID format "not-a-valid-uuid": ... } } ``` -------------------------------- ### Use Base32 Encoding/Decoding with TypeID in Go Source: https://context7.com/jetify-com/typeid-go/llms.txt Provides low-level functions for Crockford-inspired base32 encoding and decoding of UUID bytes. Useful for direct byte manipulation and validation. ```go package main import ( "fmt" "log" "go.jetify.com/typeid/v2/base32" ) func main() { // Encode UUID bytes to base32 uuidBytes := [16]byte{ 0x01, 0x8e, 0x5f, 0x71, 0x6f, 0x04, 0x7c, 0x5c, 0x81, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, } encoded := base32.EncodeToString(uuidBytes) fmt.Println("Encoded:", encoded) // Output: 01h455vb4pex5vsknk084sn02q // Decode base32 back to bytes decoded, err := base32.DecodeString(encoded) if err != nil { log.Fatal(err) } fmt.Printf("Decoded: %x\n", decoded) // Output: 018e5f716f047c5c8123456789abcdef // Validate without decoding err = base32.ValidateString("01h455vb4pex5vsknk084sn02q") if err != nil { log.Fatal(err) } fmt.Println("Valid base32 string") // Append-style encoding for buffer reuse var buf []byte buf = base32.AppendEncode(buf, uuidBytes) fmt.Println("Appended:", string(buf)) // Output: 01h455vb4pex5vsknk084sn02q } ``` -------------------------------- ### Generate TypeID with MustGenerate (Panics on Error) Source: https://context7.com/jetify-com/typeid-go/llms.txt Creates a new TypeID with a given prefix, panicking if the input is invalid. This is suitable for static, known-valid prefixes where errors indicate programming bugs. Supports bare TypeIDs. ```go package main import ( "fmt" "go.jetify.com/typeid/v2" ) func main() { // Safe to use with known-valid prefixes userID := typeid.MustGenerate("user") orderID := typeid.MustGenerate("order") productID := typeid.MustGenerate("product") fmt.Println(userID) // Output: user_01h455vb4pex5vsknk084sn02q fmt.Println(orderID) // Output: order_01h455vb4pex5vsknk084sn02r fmt.Println(productID) // Output: product_01h455vb4pex5vsknk084sn02s // Generate without prefix bareID := typeid.MustGenerate("") fmt.Println(bareID) // Output: 01h455vb4pex5vsknk084sn02t } ``` -------------------------------- ### JSON Marshaling and Unmarshaling with TypeID Source: https://context7.com/jetify-com/typeid-go/llms.txt TypeID implements `encoding.TextMarshaler` and `encoding.TextUnmarshaler` for seamless JSON serialization. Use it directly in structs for API requests and responses without custom marshaling logic. ```go package main import ( "encoding/json" "fmt" "log" "go.jetify.com/typeid/v2" ) type Product struct { ID typeid.TypeID `json:"id"` Name string `json:"name"` Price float64 `json:"price"` CategoryID typeid.TypeID `json:"category_id"` } func main() { // Marshal struct with TypeIDs to JSON product := Product{ ID: typeid.MustGenerate("product"), Name: "Mechanical Keyboard", Price: 149.99, CategoryID: typeid.MustGenerate("category"), } jsonData, err := json.MarshalIndent(product, "", " ") if err != nil { log.Fatal(err) } fmt.Println(string(jsonData)) // Output: // { // "id": "product_01h455vb4pex5vsknk084sn02q", // "name": "Mechanical Keyboard", // "price": 149.99, // "category_id": "category_01h455vb4pex5vsknk084sn02r" // } // Unmarshal JSON into struct with TypeIDs jsonPayload := `{ "id": "product_00041061050r3gg28a1c60t3gf", "name": "USB Hub", "price": 29.99, "category_id": "category_00041061050r3gg28a1c60t3gg" }` var parsed Product if err := json.Unmarshal([]byte(jsonPayload), &parsed); err != nil { log.Fatal(err) } fmt.Println("Product ID prefix:", parsed.ID.Prefix()) // Output: product fmt.Println("Category ID prefix:", parsed.CategoryID.Prefix()) // Output: category } ``` -------------------------------- ### Parse TypeID String Source: https://context7.com/jetify-com/typeid-go/llms.txt Parses a TypeID string, which can include a prefix or be a bare TypeID. Handles validation errors, including invalid formats, illegal prefix characters, and invalid base32 suffixes. Demonstrates extracting components and checking for validation errors. ```go package main import ( "errors" "fmt" "log" "go.jetify.com/typeid/v2" ) func main() { // Parse a TypeID from user input or API request tid, err := typeid.Parse("order_00041061050r3gg28a1c60t3gf") if err != nil { log.Fatal(err) } fmt.Println(tid.String()) // Output: order_00041061050r3gg28a1c60t3gf fmt.Println(tid.Prefix()) // Output: order fmt.Println(tid.Suffix()) // Output: 00041061050r3gg28a1c60t3gf fmt.Println(tid.UUID()) // Output: 00000000-0000-0000-0000-000000000000 // Parse bare TypeID (no prefix) bareTid, err := typeid.Parse("00041061050r3gg28a1c60t3gf") if err != nil { log.Fatal(err) } fmt.Println(bareTid.Prefix()) // Output: (empty string) // Handle validation errors _, err = typeid.Parse("INVALID_00041061050r3gg28a1c60t3gf") if errors.Is(err, typeid.ErrValidation) { fmt.Println("Validation failed:", err) // Output: Validation failed: typeid: prefix must contain only [a-z_], found 'I' in "INVALID" } } ``` -------------------------------- ### Create TypeID from Bytes Source: https://context7.com/jetify-com/typeid-go/llms.txt Efficiently create a TypeID from a 16-byte UUID byte slice. This method avoids string parsing overhead when UUIDs are already in binary format. Ensure the input is a valid 16-byte slice. ```go package main import ( "fmt" "log" "go.jetify.com/typeid/v2" ) func main() { // Create TypeID from raw UUID bytes uuidBytes := []byte{ 0x01, 0x8e, 0x5f, 0x71, 0x6f, 0x04, 0x7c, 0x5c, 0x81, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, } sessionID, err := typeid.FromBytes("session", uuidBytes) if err != nil { log.Fatal(err) } fmt.Println(sessionID.String()) // Output: session_01h455vb4pex5vsknk084sn02q fmt.Println(sessionID.UUID()) // Output: 018e5f71-6f04-7c5c-8123-456789abcdef // Get bytes back retrievedBytes := sessionID.Bytes() fmt.Printf("%x\n", retrievedBytes) // Output: 018e5f716f047c5c8123456789abcdef } ``` -------------------------------- ### FromUUID Source: https://context7.com/jetify-com/typeid-go/llms.txt Creates a TypeID from an existing UUID string (hex format with dashes). Useful for migrating from UUID-based systems to TypeIDs or when you need to convert between formats. ```APIDOC ## FromUUID ### Description Creates a TypeID from an existing UUID string (hex format with dashes). Useful for migrating from UUID-based systems to TypeIDs or when you need to convert between formats. ### Method `typeid.FromUUID(prefix string, uuid string) (TypeID, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "log" "go.jetify.com/typeid/v2" ) func main() { // Convert existing UUID to TypeID existingUUID := "550e8400-e29b-41d4-a716-446655440000" customerID, err := typeid.FromUUID("customer", existingUUID) if err != nil { log.Fatal(err) } fmt.Println(customerID.String()) // Output: customer_2n1t201rmv87aae5j4csam8000 fmt.Println(customerID.UUID()) // Output: 550e8400-e29b-41d4-a716-446655440000 // Round-trip verification recoveredUUID := customerID.UUID() fmt.Println(recoveredUUID == existingUUID) // Output: true // Create bare TypeID from UUID bareID, err := typeid.FromUUID("", existingUUID) if err != nil { log.Fatal(err) } fmt.Println(bareID.String()) // Output: 2n1t201rmv87aae5j4csam8000 } ``` ### Response #### Success Response (200) - **TypeID** (typeid.TypeID) - The TypeID created from the UUID. - **error** (error) - An error if the UUID format is invalid or the prefix is invalid. #### Response Example ``` customer_2n1t201rmv87aae5j4csam8000 ``` ``` -------------------------------- ### MustGenerate TypeID Source: https://context7.com/jetify-com/typeid-go/llms.txt Creates a new TypeID with the given prefix, panicking on invalid input. Use this for static prefixes known at compile time where errors indicate programming bugs rather than runtime conditions. ```APIDOC ## MustGenerate TypeID ### Description Creates a new TypeID with the given prefix, panicking on invalid input. Use this for static prefixes known at compile time where errors indicate programming bugs rather than runtime conditions. ### Method `typeid.MustGenerate(prefix string) TypeID` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "go.jetify.com/typeid/v2" ) func main() { // Safe to use with known-valid prefixes userID := typeid.MustGenerate("user") orderID := typeid.MustGenerate("order") productID := typeid.MustGenerate("product") fmt.Println(userID) // Output: user_01h455vb4pex5vsknk084sn02q fmt.Println(orderID) // Output: order_01h455vb4pex5vsknk084sn02r fmt.Println(productID) // Output: product_01h455vb4pex5vsknk084sn02s // Generate without prefix bareID := typeid.MustGenerate("") fmt.Println(bareID) // Output: 01h455vb4pex5vsknk084sn02t } ``` ### Response #### Success Response (200) - **TypeID** (typeid.TypeID) - The generated TypeID. #### Response Example ``` user_01h455vb4pex5vsknk084sn02q ``` ``` -------------------------------- ### Parse TypeID Source: https://context7.com/jetify-com/typeid-go/llms.txt Parses a TypeID string in the format `prefix_suffix` or just `suffix` (for bare TypeIDs). Returns an error if the format is invalid, the prefix contains illegal characters, or the suffix is not valid base32. ```APIDOC ## Parse TypeID ### Description Parses a TypeID string in the format `prefix_suffix` or just `suffix` (for bare TypeIDs). Returns an error if the format is invalid, the prefix contains illegal characters, or the suffix is not valid base32. ### Method `typeid.Parse(s string) (TypeID, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "errors" "fmt" "log" "go.jetify.com/typeid/v2" ) func main() { // Parse a TypeID from user input or API request tid, err := typeid.Parse("order_00041061050r3gg28a1c60t3gf") if err != nil { log.Fatal(err) } fmt.Println(tid.String()) // Output: order_00041061050r3gg28a1c60t3gf fmt.Println(tid.Prefix()) // Output: order fmt.Println(tid.Suffix()) // Output: 00041061050r3gg28a1c60t3gf fmt.Println(tid.UUID()) // Output: 00000000-0000-0000-0000-000000000000 // Parse bare TypeID (no prefix) bareTid, err := typeid.Parse("00041061050r3gg28a1c60t3gf") if err != nil { log.Fatal(err) } fmt.Println(bareTid.Prefix()) // Output: (empty string) // Handle validation errors _, err = typeid.Parse("INVALID_00041061050r3gg28a1c60t3gf") if errors.Is(err, typeid.ErrValidation) { fmt.Println("Validation failed:", err) // Output: Validation failed: typeid: prefix must contain only [a-z_], found 'I' in "INVALID" } } ``` ### Response #### Success Response (200) - **TypeID** (typeid.TypeID) - The parsed TypeID. - **error** (error) - An error if the string is not a valid TypeID. #### Response Example ``` order_00041061050r3gg28a1c60t3gf ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.