Generate Unique ID in Golang – UUID

This post explains how to Generate Unique ID in Golang. In the world of programming, generating unique identifiers is a common task, particularly when it comes to ensuring that each entity or object within an application is distinguishable from the others. For developers utilizing Go, commonly referred to as Golang, several methods exist to generate unique IDs.

Generate Unique ID in golang

Table of Contents

  1. Using the UUID Package
  2. Cryptography-Based Random IDs
  3. Timestamp-Based IDs
  4. Custom ID Generators
  5. Conclusive Summary
  6. References

 

Using the UUID Package

The UUID (Universally Unique Identifier) package is a widely adopted method for generating unique IDs. A UUID ensures that it’s highly unlikely for the same ID to be generated twice. Here’s an example of how to use it in Golang:

import (
    "fmt"
    "github.com/google/uuid"
)

func GenerateUUID() string {
    id := uuid.New()
    return id.String()
}

// Usage example:
func main() {
    uniqueID := GenerateUUID()
    fmt.Println("Generated UUID:", uniqueID)
}

Output:

Generated UUID: 123e4567-e89b-12d3-a456-426614174000

The uuid.New() function calls on the third-party UUID library to generate a unique identifier. Keep in mind that you’ll need to import the Google UUID library into your Golang project to utilize this snippet.

Cryptography-Based Random IDs

Generating IDs based on cryptography is another secure method. The crypto/rand package provides a secure RNG (Random Number Generator) that you can use to create random byte sequences, which can be converted into a hex string as an ID:

import (
    "crypto/rand"
    "encoding/hex"
    "fmt"
)

func GenerateCryptoID() string {
    bytes := make([]byte, 16)
    if _, err := rand.Read(bytes); err != nil {
        panic(err)
    }
    return hex.EncodeToString(bytes)
}

// Usage example:
func main() {
    cryptoID := GenerateCryptoID()
    fmt.Println("Generated Cryptographic ID:", cryptoID)
}

Output:

Generated Cryptographic ID: 7f4a2c70b3cd4e688dbf587c5d0b2aae

This snippet generates a 16-byte array using secure random bytes, encoding it into a hexadecimal string. The outcome is a unique and secure identifier suitable for sensitive operations.

Timestamp-Based IDs

Using timestamps is a straightforward way to generate unique identifiers, especially when combined with other data. Here’s how you can produce a simple timestamp-based ID:

import (
    "fmt"
    "time"
)

func GenerateTimestampID() string {
    return fmt.Sprintf("%d", time.Now().UnixNano())
}

// Usage example:
func main() {
    timestampID := GenerateTimestampID()
    fmt.Println("Generated Timestamp ID:", timestampID)
}

Output:

Generated Timestamp ID: 1616161895000000000

This code converts the current time into nanoseconds since the epoch, generating a unique ID based on the exact moment of its invocation. However, this method may not suit all situations, particularly those demanding more secure IDs.

Custom ID Generators

A custom ID generator allows you to tailor the ID format to your specific needs. Below is an example of a generator that merges a timestamp with a random number:

import (
    "crypto/rand"
    "fmt"
    "math/big"
    "time"
)

func GenerateCustomID() string {
    currentTime := time.Now().UnixNano()
    randomNumber, _ := rand.Int(rand.Reader, big.NewInt(1000000))
    return fmt.Sprintf("%d-%d", currentTime, randomNumber)
}

// Usage example:
func main() {
    customID := GenerateCustomID()
    fmt.Println("Generated Custom ID:", customID)
}

Output:

Generated Custom ID: 1616161895000000000-473829

This function melds a timestamp with a big integer random number, creating a more complex ID that is also significantly unique. By manipulating the formats and sources of the number, developers can generate custom IDs to fit various scenarios.

Conclusive Summary

In Golang, achieving unique ID generation involves various approaches, such as utilizing UUID libraries, cryptographic random functions, timestamps, and crafting custom solutions. The optimal method selection depends on your application’s specific needs for security, format, and predictability. The examples in this post offer a starting point to create purpose-fit IDs, ensuring consistency and uniqueness for entities in your Go applications.

References