randn

package
v0.1.12-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 11, 2026 License: GPL-3.0 Imports: 14 Imported by: 0

README

randn

randn is a Go library providing convenient utilities for generating random numbers, UUIDs, unique identifiers, and random data. It offers both simple random generation for general use and cryptographically secure generation for security-sensitive applications.

Overview

The randn package simplifies random data generation in Go by providing:

  • UUID Generation: Standard and custom-delimited UUIDs using /dev/urandom
  • Unique IDs: Alphanumeric IDs, crypto-secure IDs, and time-based IDs
  • Random Numbers: Integers, floats (32/64-bit), and ranged random values
  • Random Bytes: Generate random byte arrays for any purpose

Problem Solved: Go's standard math/rand package requires manual seeding and verbose setup. The randn package provides pre-configured, ready-to-use functions with sensible defaults, plus additional utilities like UUID and ID generation that aren't in the standard library.

Use Cases

When to Use
  • UUID generation - create unique identifiers for database records
  • Session tokens - generate secure session IDs
  • API keys - create cryptographically secure keys
  • Random IDs - generate readable alphanumeric identifiers
  • Testing data - create random test values
  • Time-based IDs - unique, sortable identifiers with timestamps
  • Random sampling - generate random numbers for algorithms
  • Game development - random values for game mechanics
  • Simulations - random data for statistical simulations
When Not to Use
  • Cryptographic keys - use dedicated crypto libraries (e.g., crypto/ecdsa, crypto/rsa)
  • Password hashing - use bcrypt, argon2, or similar
  • Cross-platform UUIDs - UUID() relies on /dev/urandom (Unix-only)
  • Deterministic randomness - when you need reproducible sequences with custom seeds
  • High-performance hot paths - consider inlining math/rand calls directly

Installation

go get github.com/sivaosorg/replify

Import the package in your Go code:

import "github.com/sivaosorg/replify/pkg/randn"

Requirements:

  • Go 1.13 or higher
  • Unix-based system for UUID functions (Linux, macOS, BSD)

Usage

Quick Start
package main

import (
    "fmt"
    "github.com/sivaosorg/replify/pkg/randn"
)

func main() {
    // Generate a UUID
    uuid, err := randn.UUID()
    if err != nil {
        panic(err)
    }
    fmt.Println("UUID:", uuid)
    // Output: UUID: a1b2c3d4-e5f6-7890-abcd-ef1234567890

    // Generate a random alphanumeric ID
    id := randn.RandID(16)
    fmt.Println("Random ID:", id)
    // Output: Random ID: aB3dE5fG7hI9jK1m

    // Generate a random integer in range
    num := randn.RandIntr(1, 100)
    fmt.Println("Random number 1-100:", num)
    // Output: Random number 1-100: 42
}

Examples

1. UUID Generation
// Standard UUID (with dashes)
uuid, err := randn.UUID()
if err != nil {
    log.Fatalf("Failed to generate UUID: %v", err)
}
fmt.Println(uuid)
// Output: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"

// UUID without dashes
uuidNoDash, err := randn.UUIDSep("")
if err != nil {
    log.Fatal(err)
}
fmt.Println(uuidNoDash)
// Output: "a1b2c3d4e5f67890abcdef1234567890"

// UUID with custom delimiter
uuidCustom, err := randn.UUIDSep(":")
fmt.Println(uuidCustom)
// Output: "a1b2c3d4:e5f6:7890:abcd:ef1234567890"

// UUID without error handling (returns empty string on error)
uuid = randn.RandUUID()
if uuid == "" {
    fmt.Println("Failed to generate UUID")
}
2. Random ID Generation
// Alphanumeric ID (length 16)
id := randn.RandID(16)
fmt.Println("Short ID:", id)
// Output: "aB3dE5fG7hI9jK1m"

// Longer ID for tokens
token := randn.RandID(32)
fmt.Println("Token:", token)
// Output: "aB3dE5fG7hI9jK1mNoP2qR4sT6uV8wX0"

// Cryptographically secure ID
secureID := randn.CryptoID()
fmt.Println("Secure ID:", secureID)
// Output: "a1b2c3d4e5f67890a1b2c3d4e5f67890" (32 hex chars)

// Time-based ID (timestamp + random)
timeID := randn.TimeID()
fmt.Println("Time ID:", timeID)
// Output: "1704067200123456789987654321"
3. Random Integers
// Random integer (full int range)
anyInt := randn.RandInt()
fmt.Println("Random int:", anyInt)
// Output: Random int: 5577006791947779410

// Random integer in range [1, 100] (inclusive)
dice100 := randn.RandIntr(1, 100)
fmt.Println("1-100:", dice100)
// Output: 1-100: 42

// Simulate dice roll (1-6)
diceRoll := randn.RandIntr(1, 6)
fmt.Println("Dice roll:", diceRoll)
// Output: Dice roll: 4

// Random year (2020-2030)
year := randn.RandIntr(2020, 2030)
fmt.Println("Random year:", year)
// Output: Random year: 2025
4. Random Floats
// Float64 in [0.0, 1.0)
probability := randn.RandFt64()
fmt.Printf("Probability: %.4f\n", probability)
// Output: Probability: 0.6046

// Float64 in custom range [10.0, 50.0)
temperature := randn.RandFt64r(10.0, 50.0)
fmt.Printf("Temperature: %.2f°C\n", temperature)
// Output: Temperature: 32.45°C

// Float32 in [0.0, 1.0)
smallProb := randn.RandFt32()
fmt.Printf("Small probability: %.4f\n", smallProb)
// Output: Small probability: 0.9451

// Float32 in custom range [-1.0, 1.0)
offset := randn.RandFt32r(-1.0, 1.0)
fmt.Printf("Offset: %.4f\n", offset)
// Output: Offset: -0.3214
5. Random Bytes
// Generate 16 random bytes
bytes := randn.RandByte(16)
fmt.Printf("Random bytes: %x\n", bytes)
// Output: Random bytes: a1b2c3d4e5f6789012345678abcdef01

// Generate salt for hashing (32 bytes)
salt := randn.RandByte(32)
fmt.Printf("Salt length: %d\n", len(salt))
// Output: Salt length: 32

// Generate IV for encryption (16 bytes)
iv := randn.RandByte(16)
// Use in your encryption scheme
6. Practical Use Cases
Database Record IDs
type User struct {
    ID        string
    Name      string
    CreatedAt time.Time
}

func NewUser(name string) (*User, error) {
    uuid, err := randn.UUID()
    if err != nil {
        return nil, fmt.Errorf("failed to generate user ID: %w", err)
    }
    
    return &User{
        ID:        uuid,
        Name:      name,
        CreatedAt: time.Now(),
    }, nil
}
Session Token Generation
type Session struct {
    Token     string
    UserID    string
    ExpiresAt time.Time
}

func CreateSession(userID string) *Session {
    return &Session{
        Token:     randn.CryptoID(), // Cryptographically secure
        UserID:    userID,
        ExpiresAt: time.Now().Add(24 * time.Hour),
    }
}
API Key Generation
func GenerateAPIKey() string {
    // Format: prefix + secure random ID
    prefix := "sk"
    randomPart := randn.CryptoID()
    return fmt.Sprintf("%s_%s", prefix, randomPart)
}

// Usage
apiKey := GenerateAPIKey()
fmt.Println(apiKey)
// Output: sk_a1b2c3d4e5f67890a1b2c3d4e5f67890
Invitation Code Generation
func GenerateInviteCode() string {
    // 8-character alphanumeric code
    return randn.RandID(8)
}

// Usage
code := GenerateInviteCode()
fmt.Println("Invite code:", code)
// Output: Invite code: aB3dE5fG
Random Test Data
type TestUser struct {
    ID    string
    Age   int
    Score float64
}

func GenerateTestUser() TestUser {
    return TestUser{
        ID:    randn.RandID(12),
        Age:   randn.RandIntr(18, 80),
        Score: randn.RandFt64r(0.0, 100.0),
    }
}
Time-Ordered IDs
// Generate sortable IDs based on timestamp
func GenerateOrderedID() string {
    return randn.TimeID()
}

// IDs will be naturally sorted by creation time
ids := []string{
    GenerateOrderedID(),
    GenerateOrderedID(),
    GenerateOrderedID(),
}
// ids are naturally in chronological order
Random Sampling
// Select random items from a list
func RandomSample(items []string, count int) []string {
    if count > len(items) {
        count = len(items)
    }
    
    selected := make([]string, 0, count)
    used := make(map[int]bool)
    
    for len(selected) < count {
        idx := randn.RandIntr(0, len(items)-1)
        if !used[idx] {
            selected = append(selected, items[idx])
            used[idx] = true
        }
    }
    
    return selected
}
Simulation Data
// Generate random sensor readings
type SensorReading struct {
    ID          string
    Timestamp   time.Time
    Temperature float64
    Humidity    float64
}

func SimulateSensorReading() SensorReading {
    return SensorReading{
        ID:          randn.RandID(8),
        Timestamp:   time.Now(),
        Temperature: randn.RandFt64r(15.0, 35.0),
        Humidity:    randn.RandFt64r(30.0, 90.0),
    }
}

API Reference

UUID Functions
Function Description Returns Error Handling
UUID() (string, error) Generate standard UUID with dashes UUID string Returns error if /dev/urandom unavailable
UUIDSep(delimiter string) (string, error) Generate UUID with custom delimiter UUID string Returns error if /dev/urandom unavailable
RandUUID() string Generate UUID without error handling UUID string or empty Returns "" on error

UUID Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (32 hex digits with dashes)

Note: UUID functions require Unix-based systems with /dev/urandom (Linux, macOS, BSD).


ID Generation Functions
Function Description Parameters Returns
RandID(length int) string Alphanumeric ID length - ID length Random string (A-Z, a-z, 0-9)
CryptoID() string Cryptographically secure hex ID None 32-character hex string
TimeID() string Timestamp-based ID None Nanosecond timestamp + random int

RandID Characters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

CryptoID: Uses crypto/rand for security-critical applications. Suitable for tokens, API keys, secrets.

TimeID: Sortable by creation time. Format: {nanoseconds}{randomint}


Random Integer Functions
Function Description Parameters Returns Range
RandInt() int Random integer None Random int Full int range
RandIntr(min, max int) int Random integer in range min, max (inclusive) Random int [min, max]

RandIntr Behavior:

  • Both bounds are inclusive: RandIntr(1, 10) can return 1 or 10
  • If min >= max, returns min
  • Automatically reseeds on each call for better randomness

Random Float Functions
Function Description Parameters Returns Range
RandFt64() float64 Random float64 None Random float64 [0.0, 1.0)
RandFt64r(start, end float64) float64 Float64 in range start, end Random float64 [start, end)
RandFt32() float32 Random float32 None Random float32 [0.0, 1.0)
RandFt32r(start, end float32) float32 Float32 in range start, end Random float32 [start, end)

Note: Upper bound is exclusive for float functions.


Random Byte Functions
Function Description Parameters Returns
RandByte(count int) []byte Generate random bytes count - number of bytes Byte slice

Use Cases:

  • Encryption IVs (Initialization Vectors)
  • Salts for password hashing
  • Random binary data
  • Nonces for cryptographic operations

Best Practices & Notes

⚠️ Common Pitfalls
  1. UUID Platform Dependency

    // ❌ Won't work on Windows
    uuid, err := randn.UUID()
    // Requires Unix-based system (/dev/urandom)
    
    // ✅ Always check for errors
    uuid, err := randn.UUID()
    if err != nil {
        // Fallback to another method or handle error
        log.Printf("UUID generation failed: %v", err)
    }
    
  2. RandIntr Range Confusion

    // ✅ Correct: both bounds inclusive
    dice := randn.RandIntr(1, 6)  // Can return 1, 2, 3, 4, 5, or 6
    
    // ❌ Common mistake: forgetting upper bound is inclusive
    index := randn.RandIntr(0, len(slice))  // Wrong! Can exceed slice bounds
    
    // ✅ Correct: adjust upper bound
    index := randn.RandIntr(0, len(slice)-1)
    
  3. Float Range Boundaries

    // Note: upper bound is exclusive for floats
    val := randn.RandFt64r(0.0, 1.0)  // Returns [0.0, 1.0)
    // Can be 0.0, but will never be exactly 1.0
    
  4. Security vs Performance

    // ❌ Don't use RandID for security-critical tasks
    apiKey := randn.RandID(32)  // Not cryptographically secure
    
    // ✅ Use CryptoID for security
    apiKey := randn.CryptoID()  // Cryptographically secure
    
💡 Recommendations

Use appropriate functions for the task

// For database IDs (readability + uniqueness)
userID := randn.UUID()

// For human-readable codes (invites, vouchers)
code := randn.RandID(8)

// For security tokens (sessions, API keys)
token := randn.CryptoID()

// For sortable IDs (logs, events)
logID := randn.TimeID()

Error handling for UUIDs

// Always handle UUID errors in production
uuid, err := randn.UUID()
if err != nil {
    // Log error and use fallback
    log.Printf("UUID generation failed: %v", err)
    uuid = randn.TimeID() // Fallback
}

Validate ranges before calling RandIntr

func RandomIndex(sliceLen int) int {
    if sliceLen <= 0 {
        return 0
    }
    return randn.RandIntr(0, sliceLen-1)
}

Use appropriate ID lengths

// Short codes (human-readable): 6-8 characters
inviteCode := randn.RandID(8)

// Standard IDs (good uniqueness): 16 characters
recordID := randn.RandID(16)

// Long tokens (high uniqueness): 32+ characters
sessionToken := randn.RandID(32)

Prefix IDs for identification

func GenerateUserID() string {
    return "usr_" + randn.RandID(16)
}

func GenerateOrderID() string {
    return "ord_" + randn.RandID(16)
}
🔒 Security Considerations

When to use CryptoID:

  • ✅ API keys
  • ✅ Session tokens
  • ✅ OAuth secrets
  • ✅ Encryption keys
  • ✅ Password reset tokens
  • ✅ CSRF tokens

When RandID is sufficient:

  • ✅ Non-sensitive unique IDs
  • ✅ Test data
  • ✅ Temporary identifiers
  • ✅ Display-only codes
  • ✅ Gaming/simulation

Security notes:

// ❌ Don't use for cryptographic keys
key := randn.RandByte(32)  // Uses math/rand, not crypto/rand

// ✅ Use crypto/rand for sensitive data
import "crypto/rand"
key := make([]byte, 32)
rand.Read(key)
⚡ Performance Tips

Fast operations (math/rand):

  • RandInt(), RandIntr() - Very fast
  • RandFt64(), RandFt32() - Very fast
  • RandID() - Fast for short lengths
  • RandByte() - Fast

Moderate operations:

  • UUID(), RandUUID() - File I/O overhead
  • UUIDSep() - File I/O overhead
  • TimeID() - System call overhead

Slower operations (crypto/rand):

  • CryptoID() - Cryptographically secure, slower

Optimization strategies:

// ✅ Generate IDs in batch for better performance
func GenerateBatchIDs(count int) []string {
    ids := make([]string, count)
    for i := 0; i < count; i++ {
        ids[i] = randn.RandID(16)
    }
    return ids
}

// ✅ Reuse byte slices
func ReuseByteSlice() {
    buffer := make([]byte, 16)
    for i := 0; i < 1000; i++ {
        buffer = randn.RandByte(16)
        // Use buffer
    }
}
🐛 Debugging Tips

Check UUID generation:

uuid, err := randn.UUID()
if err != nil {
    fmt.Printf("UUID Error: %v\n", err)
    fmt.Println("Check if /dev/urandom is available")
}
fmt.Printf("UUID: %s (length: %d)\n", uuid, len(uuid))

Verify randomness:

// Generate multiple values to check distribution
for i := 0; i < 10; i++ {
    fmt.Println(randn.RandIntr(1, 10))
}

Test edge cases:

// Same min and max
fmt.Println(randn.RandIntr(5, 5))  // Always returns 5

// Invalid range
fmt.Println(randn.RandIntr(10, 5)) // Returns 10 (min)
🔧 Thread Safety

The package uses a package-level random generator that is NOT thread-safe for the custom functions (RandIntr).

// ⚠️ Not thread-safe without synchronization
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        randn.RandIntr(1, 100) // Potential race condition
    }()
}

// ✅ Thread-safe with mutex
var mu sync.Mutex
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        val := randn.RandIntr(1, 100)
        mu.Unlock()
        // Use val
    }()
}

Note: Standard math/rand functions (RandInt, RandFt64, etc.) use the global generator which has internal locking in Go 1.6+.

📝 Testing

Example test cases:

func TestUUIDFormat(t *testing.T) {
    uuid, err := randn.UUID()
    if err != nil {
        t.Skip("Skipping UUID test (requires /dev/urandom)")
    }
    
    // Check format (8-4-4-4-12)
    if len(uuid) != 36 {
        t.Errorf("UUID length = %d, want 36", len(uuid))
    }
    
    // Check dashes at correct positions
    if uuid[8] != '-' || uuid[13] != '-' || uuid[18] != '-' || uuid[23] != '-' {
        t.Errorf("UUID format incorrect: %s", uuid)
    }
}

func TestRandIntrRange(t *testing.T) {
    min, max := 1, 10
    for i := 0; i < 1000; i++ {
        val := randn.RandIntr(min, max)
        if val < min || val > max {
            t.Errorf("RandIntr(%d, %d) = %d, out of range", min, max, val)
        }
    }
}

func TestRandIDLength(t *testing.T) {
    lengths := []int{8, 16, 32, 64}
    for _, length := range lengths {
        id := randn.RandID(length)
        if len(id) != length {
            t.Errorf("RandID(%d) length = %d, want %d", length, len(id), length)
        }
    }
}

Limitations

  • Platform-specific: UUID functions require Unix-based systems (/dev/urandom)
  • Not cryptographically secure: Most functions use math/rand (except CryptoID)
  • Thread safety: RandIntr is not thread-safe without external synchronization
  • No UUID version support: Generated UUIDs don't follow UUID v4 spec exactly
  • No custom seeding: Cannot set custom seed for reproducibility

Migration from Standard Library

// Before (math/rand)
import "math/rand"
rand.Seed(time.Now().UnixNano())
val := rand.Intn(100)

// After (randn)
import "github.com/sivaosorg/replify/pkg/randn"
val := randn.RandIntr(0, 99)

Contributing

Contributions are welcome! Please see the main replify repository for contribution guidelines.

License

This library is part of the replify project.

Part of the replify ecosystem:

  • replify - API response wrapping library
  • conv - Type conversion utilities
  • hashy - Deterministic hashing
  • match - Wildcard pattern matching
  • coll - Collection utilities
  • strutil - String utilities

Documentation

Overview

Package randn provides functions for generating random values, unique identifiers, and universally unique identifiers (UUIDs).

UUID and UUIDSep use crypto/rand to produce RFC 4122 version-4 UUIDs and are safe on all platforms (Linux, macOS, Windows, and others). RandID and the numeric functions rely on the goroutine-safe global math/rand source (automatically seeded in Go 1.20+) and are not cryptographically secure; use CryptoID when security properties matter.

Identifiers

randn.UUID()         // standard UUID, e.g. "550e8400-e29b-41d4-a716-446655440000"
randn.UUIDSep("/")  // UUID with a custom delimiter
randn.RandUUID()     // UUID, empty string on error
randn.RandID(16)     // 16-character alphanumeric string (math/rand)
randn.CryptoID()     // 32-character hex string (crypto/rand)
randn.TimeID()       // nanosecond timestamp + random int, as a string
randn.NewXID()       // unique 20-character identifier (rs/xid port)

Numeric Values

randn.RandInt()            // random int
randn.RandIntr(min, max)   // random int in [min, max] inclusive
randn.RandFt64()           // random float64 in [0.0, 1.0)
randn.RandFt64r(lo, hi)    // random float64 in [lo, hi)
randn.RandFt32()           // random float32 in [0.0, 1.0)
randn.RandFt32r(lo, hi)    // random float32 in [lo, hi)
randn.RandByte(n)          // slice of n random bytes

All functions in this package are safe for concurrent use.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidID is returned when trying to unmarshal an invalid ID
	ErrInvalidID = errors.New("randn: invalid XID")
)

Functions

func CryptoID

func CryptoID() string

CryptoID generates a cryptographically secure random ID as a hexadecimal string. It uses 16 random bytes, which are then encoded to a hexadecimal string for easy representation.

Returns:

  • A string representing a secure random hexadecimal ID of 32 characters (since 16 bytes are used, and each byte is represented by two hexadecimal characters).

The function uses crypto/rand.Read to ensure cryptographic security in the generated ID, making it suitable for sensitive use cases such as API keys, session tokens, or any security-critical identifiers.

Example:

id := CryptoID()
fmt.Println("Generated Crypto ID:", id)

Notes:

  • This function is suitable for use cases where high security is required in the generated ID.
  • It is not recommended for use cases where deterministic or non-cryptographic IDs are preferred.

func RandByte

func RandByte(count int) []byte

RandByte creates an array of random bytes with the specified length.

Parameters:

  • `count`: The number of random bytes to generate.

Returns:

  • A slice of random bytes with the specified length.

func RandFt32

func RandFt32() float32

RandFt32 returns the next random float32 value in the range [0.0, 1.0).

This function uses the rand package to generate a random float32 value. The generated value is uniformly distributed over the interval [0.0, 1.0).

Returns:

  • A random float32 value between 0.0 and 1.0.

func RandFt32r

func RandFt32r(start float32, end float32) float32

RandFt32r returns the next random float32 value bounded by the specified range.

Parameters:

  • `start`: The lower bound of the random float32 value (inclusive).
  • `end`: The upper bound of the random float32 value (exclusive).

Returns:

  • A random float32 value uniformly distributed between `start` and `end`.

func RandFt64

func RandFt64() float64

RandFt64 returns the next random float64 value in the range [0.0, 1.0).

This function uses the rand package to generate a random float64 value. The generated value is uniformly distributed over the interval [0.0, 1.0).

Returns:

  • A random float64 value between 0.0 and 1.0.

func RandFt64r

func RandFt64r(start float64, end float64) float64

RandFt64r returns the next random float64 value bounded by the specified range.

Parameters:

  • `start`: The lower bound of the random float64 value (inclusive).
  • `end`: The upper bound of the random float64 value (exclusive).

Returns:

  • A random float64 value uniformly distributed between `start` and `end`.

func RandID

func RandID(length int) string

RandID generates a random alphanumeric string of the specified length. This string includes uppercase letters, lowercase letters, and numbers, making it suitable for use as unique IDs or tokens.

Parameters:

  • length: The length of the random ID to generate. Must be a positive integer.

Returns:

  • A string of random alphanumeric characters with the specified length.

The function uses the goroutine-safe global math/rand source (automatically seeded in Go 1.20+). This function is intended to generate random strings quickly and is not cryptographically secure.

Example:

id := RandID(16)
fmt.Println("Generated Random ID:", id)

Notes:

  • This function is suitable for use cases where simple random IDs are needed. However, for cryptographic purposes, consider using CryptoID instead.

func RandIDHex added in v0.1.11

func RandIDHex(byteLen int) string

RandIDHex produces a cryptographically random identifier of the specified byte length, returned as a hex-encoded string. The resulting string length is 2x the requested byte count.

This replaces the use of math/rand, providing collision-resistant identifiers suitable for concurrent operations.

Example:

id := RandIDHex(8)
fmt.Println(len(id)) // 16

func RandInt

func RandInt() int

RandInt returns the next random int value.

This function uses the rand package to generate a random int value. Returns:

  • A random int value.

func RandIntr

func RandIntr(min, max int) int

RandIntr generates a random integer within the specified range [min, max], inclusive.

If the provided min is greater than or equal to max, the function returns min as a default value.

The function uses the goroutine-safe global math/rand source (automatically seeded in Go 1.20+) and is safe for concurrent use without external synchronization.

Parameters:

  • `min`: The lower bound of the random number range (inclusive).
  • `max`: The upper bound of the random number range (inclusive).

Returns:

  • A random integer between `min` and `max`, including both bounds.

Example:

randomNum := RandIntr(1, 10)
fmt.Println("Random number between 1 and 10:", randomNum)

func RandUUID

func RandUUID() string

RandUUID generates and returns a new UUID (RFC 4122 version 4).

If an error occurs during UUID generation, the function returns an empty string.

This function is useful when you want a simple UUID generation without handling errors directly. It abstracts away the error handling by returning an empty string in case of failure.

Returns:

  • A string representing the newly generated UUID.
  • An empty string if an error occurs during UUID generation.

Example:

uuid := RandUUID()

if uuid == "" {
    fmt.Println("Failed to generate UUID")
} else {

    fmt.Println("Generated UUID:", uuid)
}

func RandUint32 added in v0.1.11

func RandUint32() uint32

RandUint32 returns the next random uint32 value.

This function uses the crypto/rand package to generate a random uint32 value.

Returns:

  • A random uint32 value.

Example:

randomNum := RandUint32()
fmt.Println("Random number between 1 and 10 after reseeding:", randomNum)

func TimeID

func TimeID() string

TimeID generates a unique identifier based on the current Unix timestamp in nanoseconds, with an additional random integer to enhance uniqueness.

This function captures the current time in nanoseconds since the Unix epoch and appends a random integer to ensure additional randomness and uniqueness, even if called in rapid succession. The result is returned as a string. This type of ID is well-suited for time-based ordering and can be useful for generating unique identifiers for logs, events, or non-cryptographic applications.

Returns:

  • A string representing the current Unix timestamp in nanoseconds, concatenated with a random integer.

Example:

id := TimeID()
fmt.Println("Generated Timestamp ID:", id)

Notes:

  • This function provides a unique, time-ordered identifier, but it is not suitable for cryptographic use.
  • The combination of the current time and a random integer is best suited for applications requiring uniqueness and ordering, rather than secure identifiers.

func UUID

func UUID() (string, error)

UUID generates a new universally unique identifier (UUID) (RFC 4122 version 4) using crypto/rand for cryptographically secure randomness.

UUID Format: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX (version 4, variant 1).

Returns:

  • A string representing the newly generated UUID.
  • An error if the random source is unavailable.

Example:

uuid, err := UUID()
if err != nil {
    log.Fatalf("Failed to generate UUID: %v", err)
}
fmt.Println("Generated UUID:", uuid)

func UUIDSep added in v0.1.11

func UUIDSep(delimiter string) (string, error)

UUIDSep generates a new universally unique identifier (UUID) (RFC 4122 version 4) using crypto/rand, with a customizable delimiter between UUID sections.

This function is cross-platform: it does not rely on /dev/urandom or any OS-specific file, and works correctly on Linux, macOS, Windows, and other platforms supported by the Go crypto/rand package.

Parameters:

  • delimiter: A string used to separate sections of the UUID. Common choices are "-" or "".

Returns:

  • A string representing the newly generated UUID with the specified delimiter.
  • An error if crypto/rand fails to produce random bytes.

Example:

uuid, err := UUIDSep("-")
if err != nil {
    log.Fatalf("Failed to generate UUID: %v", err)
}
fmt.Println("Generated UUID:", uuid)

Types

type XID added in v0.1.11

type XID [12]byte

XID represents a unique request id, cloned and improved from rs/xid. It is a 12-byte identifier composed of a 4-byte timestamp, 3-byte machine ID, 2-byte process ID, and a 3-byte counter.

func NewXID added in v0.1.11

func NewXID() XID

NewXID generates a new unique XID using the current time.

Example
id := NewXID()
fmt.Printf("XID: %s\n", id.String())
fmt.Printf("Time: %s\n", id.Time().UTC())

func NewXIDWithTime added in v0.1.11

func NewXIDWithTime(t time.Time) XID

NewXIDWithTime generates a new unique XID using the provided time.

func (XID) Compare added in v0.1.11

func (id XID) Compare(other XID) int

Compare compares two XIDs. It returns -1 if id < other, 1 if id > other, and 0 if they are equal.

func (XID) IsZero added in v0.1.11

func (id XID) IsZero() bool

IsZero returns true if the XID is the zero value.

func (*XID) Scan added in v0.1.11

func (id *XID) Scan(value any) error

Scan implements the database/sql.Scanner interface.

func (XID) String added in v0.1.11

func (id XID) String() string

String returns the base32 hex lowercased string representation of the ID. The output is 20 characters long.

func (XID) Time added in v0.1.11

func (id XID) Time() time.Time

Time extracts the time component from the ID.

func (*XID) Unmarshal added in v0.1.11

func (id *XID) Unmarshal(text []byte) error

Unmarshal decodes a 20-byte base32 hex lowercased representation into the XID.

func (XID) Value added in v0.1.11

func (id XID) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL