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

Here is an example code to create a random password of length 12 with uppercase letters, lowercase letters, and numbers:

main.go
package main

import (
	"math/rand"
	"time"
)

func generatePassword(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))
	password := make([]byte, length)
	for i := range password {
		password[i] = charset[seededRand.Intn(len(charset))]
	}
	return string(password)
}

func main() {
	password := generatePassword(12)
	println(password)
}
451 chars
22 lines

This code generates a random password string with the specified length using a secure seeding approach. The charset variable contains all the allowable characters in the password including uppercase and lowercase letters as well as numbers. We use the rand.NewSource() function with the current time in nanoseconds to seed the random number generator. Finally, we loop through the password array and set each character to a random character from the charset.

gistlibby LogSnag