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() }