File size: 1,566 Bytes
60e50b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package tools

import (
	"math/rand"
	"strings"
	"time" // Required for seeding math/rand
)

// init function is automatically called once when the package is initialized.
// We use it to seed the default math/rand source.
func init() {
	rand.Seed(time.Now().UnixNano())
}

// GenerateRandomString generates a random string of a given length
// using alphanumeric characters (uppercase, lowercase, and digits).
// This method is suitable for general purposes but not for cryptographically
// secure applications.
func GenerateRandomString(length int) string {
	// Define the character set to choose from
	const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

	// Create a byte slice to store the random characters
	result := make([]byte, length)

	// Iterate up to the desired length
	for i := 0; i < length; i++ {
		// Pick a random index from the charset
		randomIndex := rand.Intn(len(charset))
		// Assign the character at the random index to the result slice
		result[i] = charset[randomIndex]
	}

	// Convert the byte slice to a string and return
	return string(result)
}

// GenerateRandomStringBuilder is an optimized version using strings.Builder
// for better performance when generating longer strings.
func GenerateRandomStringBuilder(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	var sb strings.Builder
	sb.Grow(length) // Pre-allocate memory for efficiency

	for i := 0; i < length; i++ {
		randomIndex := rand.Intn(len(charset))
		sb.WriteByte(charset[randomIndex])
	}
	return sb.String()
}