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 ¶
- Variables
- func CryptoID() string
- func RandByte(count int) []byte
- func RandFt32() float32
- func RandFt32r(start float32, end float32) float32
- func RandFt64() float64
- func RandFt64r(start float64, end float64) float64
- func RandID(length int) string
- func RandIDHex(byteLen int) string
- func RandInt() int
- func RandIntr(min, max int) int
- func RandUUID() string
- func RandUint32() uint32
- func TimeID() string
- func UUID() (string, error)
- func UUIDSep(delimiter string) (string, error)
- type XID
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
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
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
NewXIDWithTime generates a new unique XID using the provided time.
func (XID) Compare ¶ added in v0.1.11
Compare compares two XIDs. It returns -1 if id < other, 1 if id > other, and 0 if they are equal.
func (XID) String ¶ added in v0.1.11
String returns the base32 hex lowercased string representation of the ID. The output is 20 characters long.