How to Generate a 4-digit Random Unique Number Using Go?

Hello Friends Today, through this tutorial, I will tell you how to generate a 4-digit random unique OTP number using Go Language Program?

Here’s how to generate a 4-digit random unique OTP number using Go:

package main

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

func generateUniqueOTP(pool string, length int) (string, error) {
// Create a byte slice to hold the generated OTP
otp := make([]byte, length)

// Use crypto/rand to generate random bytes
_, err := rand.Read(otp)
if err != nil {
return "", err
}

// Convert random bytes to a string using the provided pool
for i, b := range otp {
index, err := rand.Int(rand.Reader, big.NewInt(int64(len(pool))))
if err != nil {
return "", err
}
otp[i] = pool[index.Int64()]
}
return string(otp), nil
}
func main() {
// Define the pool of characters to use for the OTP
pool := "0123456789"
length := 4
// Generate a unique OTP
otp, err := generateUniqueOTP(pool, length)
if err != nil {
fmt.Println("Error generating OTP:", err)
return
}
fmt.Println("Generated unique OTP:", otp)
}

Explanation-

`generateUniqueOTP` function:

1. Takes a string `pool` containing the characters allowed in the OTP and the desired length `length` as arguments.
2. Creates a byte slice `otp` with the desired length to hold the generated OTP.
3. Uses `crypto/rand.Read` to fill the `otp` slice with random bytes.
4. Iterates through each byte in `otp`:
5. Uses `rand.Int` to generate a random index within the length of the `pool` string.
6. Replaces the current byte in `otp` with the character at the random index from the `pool` string.
7. Returns the generated OTP as a string and any potential error.

`main` function:

1. Defines the `pool` of characters (digits in this case) and the desired length for the OTP.
2. Calls the `generateUniqueOTP` function and stores the generated OTP and any error in variables.
3. Prints the generated OTP if successful or the error message if encountered.

This code utilizes the `crypto/rand` package to generate cryptographically secure random bytes, ensuring the generated OTP is unpredictable. It then converts the random bytes to characters using the provided pool, resulting in a unique 4-digit number.