create a password with uppercase, lowercase letters, numbers and symbols in go

To generate a secure password containing uppercase, lowercase letters, numbers and symbols in Go, we can use the math/rand and time packages to generate random characters and strconv package to convert integer to string.

Here's an example function that generates a random password:

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

func generatePassword(length int) string {
    letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()")
    rand.Seed(time.Now().UnixNano())
    password := make([]rune, length)
    for i := range password {
        password[i] = letters[rand.Intn(len(letters))]
    }
    return string(password)
}
389 chars
16 lines

In this function, we first define a slice of runes that contains all the characters we want in our password. We then use the rand.Seed function to seed the random number generator with the current time. We then create a slice of runes representing the password and loop through it randomly selecting a character from the letters slice and assigning it to the current index in the password slice.

The rand.Intn(len(letters)) expression gets a random integer between 0 and the length of the letters slice - 1, which is then used to select a random character.

Finally, we convert the slice of runes to a string and return it as the generated password.

To use this function, we just need to pass it the length of the password we want to generate:

main.go
password := generatePassword(16)
fmt.Println(password) // Example output: fN&9$Ql1@d4Idy*p
91 chars
3 lines

gistlibby LogSnag