From 1a9938ec580ab4f3fc88af96ba3a0a3c10ddd9c5 Mon Sep 17 00:00:00 2001 From: H0llyW00dzZ Date: Thu, 7 Dec 2023 12:14:36 +0700 Subject: [PATCH] Refactor [Common] [Utils] - [+] refactor(utils.go): remove deprecated init function and use local random generator in GenerateKey and GetRandomString functions - [+] chore(utils.go): add comment to explain the purpose of newRand function --- common/utils.go | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/common/utils.go b/common/utils.go index 21bec8f5..962e66e4 100644 --- a/common/utils.go +++ b/common/utils.go @@ -2,7 +2,6 @@ package common import ( "fmt" - "github.com/google/uuid" "html/template" "log" "math/rand" @@ -13,6 +12,8 @@ import ( "strconv" "strings" "time" + + "github.com/google/uuid" ) func OpenBrowser(url string) { @@ -137,15 +138,23 @@ func GetUUID() string { const keyChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" -func init() { - rand.Seed(time.Now().UnixNano()) +// Remove this function as it's no longer needed. (depcrecated) +// Note: This function required go 1.20+ +// func init() { +// rand.Seed(time.Now().UnixNano()) +// } + +// newRand creates a new instance of a random generator. +func newRand() *rand.Rand { + return rand.New(rand.NewSource(time.Now().UnixNano())) } +// GenerateKey creates a new key string. func GenerateKey() string { - rand.Seed(time.Now().UnixNano()) + localRand := newRand() // Use the local random generator key := make([]byte, 48) for i := 0; i < 16; i++ { - key[i] = keyChars[rand.Intn(len(keyChars))] + key[i] = keyChars[localRand.Intn(len(keyChars))] } uuid_ := GetUUID() for i := 0; i < 32; i++ { @@ -158,11 +167,12 @@ func GenerateKey() string { return string(key) } +// GetRandomString generates a random string of a specified length. func GetRandomString(length int) string { - rand.Seed(time.Now().UnixNano()) + localRand := newRand() // Use the local random generator key := make([]byte, length) for i := 0; i < length; i++ { - key[i] = keyChars[rand.Intn(len(keyChars))] + key[i] = keyChars[localRand.Intn(len(keyChars))] } return string(key) }