GeneratePassword() is a function that generates a strongly typed random string of the specified length (length int) and returns it as a string (string). The string is generated using a combination of lowercase, uppercase letters, numbers, and special characters.
Parameters:
- length: the length of the generated password (int)
Returns:
- string: the generated password (string)
func GeneratePassword(length int) string {
// Define the charset for generating the password
// The charset includes lowercase letters, uppercase letters, numbers, and special characters
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()+,-.:;<=>?[]_{}"
// Create a strings.Builder to store the generated password
var password strings.Builder
// Reserve memory for the password
password.Grow(length)
// Generate the password by selecting a random character from the charset for each index in the password
for i := 0; i < length; i++ {
password.WriteByte(charset[rand.Intn(len(charset))])
}
// Return the generated password
return password.String()
}
is using other functions to generate a random string of the specified length check it out, but update charset with your own.
Experience the magic of coding unfold as you execute this code!
package main
import (
"fmt"
"math/rand"
"strings"
)
func GeneratePassword(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()+,-.:;<=>?[]_{}"
var password strings.Builder
password.Grow(length)
for i := 0; i < length; i++ {
password.WriteByte(charset[rand.Intn(len(charset))])
}
return password.String()
}
func main() {
fmt.Println(GeneratePassword(12)) // Output always random Example; boj3A3#_GVTY
fmt.Println("Build with love by Adam Nasrudin")
}
enjoy your code!