create a password with at least one symbol in go

To create a password with at least one symbol in Go, you can use the crypto/rand package to generate a random password and then ensure that it has at least one symbol. Here's an example:

main.go
import (
    "crypto/rand"
    "math/big"
)

func generatePassword(length int) string {
    const symbols = "!@#$%^&*()_+{}[];':\",./<>?"
    const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    var password strings.Builder
    for i := 0; i < length; i++ {
        if i == 0 {
            // Always start with a letter
            randIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
            password.WriteByte(letters[randIndex.Int64()])
        } else if i == length-1 {
            // Always end with a symbol
            randIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(symbols))))
            password.WriteByte(symbols[randIndex.Int64()])
        } else {
            // Randomly choose a letter or symbol
            randIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(letters)+len(symbols)-1)))
            if randIndex.Int64() < int64(len(letters)) {
                password.WriteByte(letters[randIndex.Int64()])
            } else {
                password.WriteByte(symbols[randIndex.Int64()-int64(len(letters))])
            }
        }
    }
    return password.String()
}
1160 chars
31 lines

This function generates a random password with the specified length, starting with a letter and ending with a symbol. The middle characters can be either letters or symbols. The symbols are stored in a constant string and randomly selected using the crypto/rand package.

gistlibby LogSnag