create a password with numbers in go

To generate a random password with numbers in Go, you can use the math/rand package to generate random numbers and strings. Here is an example function that generates a password with a given length and at least one digit:

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

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

    const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    var password strings.Builder
    for i := 0; i < length; i++ {
        password.WriteByte(letters[rand.Intn(len(letters))])
    }

    numIndex := rand.Intn(length - 1)
    password.WriteByte('0' + byte(rand.Intn(10)))
    pw := []byte(password.String())
    pw[numIndex], pw[length-1] = pw[length-1], pw[numIndex]
    return string(pw)
}
546 chars
21 lines

This function generates a password of a given length by selecting random characters from a pool of letters and digits. It then adds one random digit to the password and swaps it with a non-digit character to ensure that there is at least one digit in the password.

You can call this function like this:

main.go
password := randomPassword(12)
fmt.Println(password)
53 chars
3 lines

This will generate a random password with 12 characters, including at least one digit.

gistlibby LogSnag