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
This commit is contained in:
H0llyW00dzZ 2023-12-07 12:14:36 +07:00
parent 01f7b0186f
commit 1a9938ec58
No known key found for this signature in database
GPG Key ID: 05C7FFFC0845C930

View File

@ -2,7 +2,6 @@ package common
import ( import (
"fmt" "fmt"
"github.com/google/uuid"
"html/template" "html/template"
"log" "log"
"math/rand" "math/rand"
@ -13,6 +12,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/google/uuid"
) )
func OpenBrowser(url string) { func OpenBrowser(url string) {
@ -137,15 +138,23 @@ func GetUUID() string {
const keyChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const keyChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func init() { // Remove this function as it's no longer needed. (depcrecated)
rand.Seed(time.Now().UnixNano()) // 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 { func GenerateKey() string {
rand.Seed(time.Now().UnixNano()) localRand := newRand() // Use the local random generator
key := make([]byte, 48) key := make([]byte, 48)
for i := 0; i < 16; i++ { for i := 0; i < 16; i++ {
key[i] = keyChars[rand.Intn(len(keyChars))] key[i] = keyChars[localRand.Intn(len(keyChars))]
} }
uuid_ := GetUUID() uuid_ := GetUUID()
for i := 0; i < 32; i++ { for i := 0; i < 32; i++ {
@ -158,11 +167,12 @@ func GenerateKey() string {
return string(key) return string(key)
} }
// GetRandomString generates a random string of a specified length.
func GetRandomString(length int) string { func GetRandomString(length int) string {
rand.Seed(time.Now().UnixNano()) localRand := newRand() // Use the local random generator
key := make([]byte, length) key := make([]byte, length)
for i := 0; i < length; i++ { for i := 0; i < length; i++ {
key[i] = keyChars[rand.Intn(len(keyChars))] key[i] = keyChars[localRand.Intn(len(keyChars))]
} }
return string(key) return string(key)
} }