create a password with a custom length and lowercase letters in go

Here's an example function that generates a random password with a custom length and only lowercase letters using Go's built-in crypto/rand package:

main.go
package main

import (
    "crypto/rand"
    "math/big"
)

func generatePassword(length int) string {
    const lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
    var password string
    for i := 0; i < length; i++ {
        randomIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(lowercaseLetters))))
        password += string(lowercaseLetters[randomIndex.Int64()])
    }
    return password
}

func main() {
    password := generatePassword(8) // generate a password with length 8
    fmt.Println(password)
}
518 chars
22 lines

In this example, we define a constant string lowercaseLetters that contains all the lowercase letters we want to use in our password. Then, we generate a random index between 0 and the length of lowercaseLetters using crypto/rand's Int function. Finally, we append the character at that index to our password string. We repeat this process until we have generated a password of the desired length.

gistlibby LogSnag