create a password with at least one uppercase letter in go

To create a password with at least one uppercase letter in Go, we can use the math/rand and time packages to generate a random string and the strings package to manipulate the string. Here's an example function that creates a password with one uppercase letter:

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

func generatePassword() string {
    rand.Seed(time.Now().UnixNano())

    // Set the length of the password
    length := 10

    // Create a random string of lowercase letters
    lower := "abcdefghijklmnopqrstuvwxyz"
    var builder strings.Builder
    for i := 0; i < length; i++ {
        builder.WriteByte(lower[rand.Intn(len(lower))])
    }

    // Replace a random character with an uppercase letter
    builder.WriteByte(lower[rand.Intn(length)])
    builder.WriteByte('A' + byte(rand.Intn(26)))

    // Shuffle the characters
    result := builder.String()
    shuffled := strings.Split(result, "")
    rand.Shuffle(len(shuffled), func(i, j int) {
        shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
    })
    result = strings.Join(shuffled, "")

    return result
}
839 chars
34 lines

This function creates a random string with lowercase letters first, then replaces a random character with an uppercase letter using the A character as the starting point and the byte type to convert the uppercase letter to a number that can be generated randomly. Finally, the function shuffles the characters before returning the password. By setting the length variable to a different value, you can control the length of the password.

gistlibby LogSnag