create a password with a custom length and numbers in go

Here is a code snippet in Go that generates a random password with a custom length (as input by the user) and includes numbers:

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

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

    // characters pool for password generation
    characters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

    // generate random password
    password := make([]rune, length)
    for i := range password {
        password[i] = characters[rand.Intn(len(characters))]
    }

    return string(password)
}
456 chars
20 lines

To use this code, simply call the generatePassword function with the desired length:

main.go
password := generatePassword(10) // generates a random password with 10 characters
83 chars
2 lines

This will generate a random password of the specified length, consisting of upper-case and lower-case letters, as well as numbers.

gistlibby LogSnag