One way to create a random password with a custom length and uppercase letters in go is to use a combination of the math/rand and time packages. The math/rand package provides functions to generate random numbers while the time package can be used to seed the random number generator.
main.go478 chars24 linesIn this code, we first define a constant letters which contains all the possible characters that can be in the password. Then we create a function generatePassword which takes an int parameter length and returns a string. Inside this function, we seed the random number generator using the time.Now().UnixNano() function, which returns the current Unix timestamp in nanoseconds. Then, we loop length number of times and select a random character from the letters string using the rand.Intn() function. Finally, we append the selected character to the password string and return it.
To include uppercase letters only, we can modify the letters constant to include only uppercase letters.
main.go45 chars2 lines
To include both lowercase and uppercase letters, we can leave the letters constant as is. Finally, to improve the security of this password generation code, we can add additional complexity rules such as including special characters or enforcing a minimum length.
gistlibby LogSnag