create a password with at least one lowercase letter in go

Here's an example code snippet in Go to generate a random password with at least one lowercase letter:

main.go
import (
    "math/rand"
    "time"
)

func generatePassword(length int) string {
    // Seed the random number generator with current time
    rand.Seed(time.Now().UnixNano())

    // Define the character set for the password
    charSet := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*"

    // Convert charSet string to an array of characters
    charSetArr := []rune(charSet)

    // Create a slice to store the password
    password := make([]rune, length)

    for i := 0; i < length; i++ {
        // Randomly select a character from charSetArr
        index := rand.Intn(len(charSetArr))
        password[i] = charSetArr[index]
    }

    // Check if password has at least one lowercase letter
    for i := 0; i < length; i++ {
        if 'a' <= password[i] && password[i] <= 'z' {
            // The password has at least one lowercase letter
            return string(password)
        }
    }

    // If password does not have a lowercase letter, recursively call the function to generate a new password
    return generatePassword(length)
}
1079 chars
36 lines

In the above code, we defined a character set that contains uppercase letters, lowercase letters, numbers, and special characters. We then used the math/rand package to randomly select characters from the character set to create a password. Finally, we checked if the password contains at least one lowercase letter. If it does, we return the password. If not, we recursively call the function to generate a new password.

gistlibby LogSnag