create a password with a custom length and symbols in go

To create a password with a custom length and symbols, you can use Go's cryptography package which provides a strong random generator.

Here's an example code snippet that generates a random string of length n with a mix of alphabetic and symbolic characters:

main.go
import (
    "crypto/rand"
    "encoding/base64"
)

func RandomString(n int) string {
    b := make([]byte, n)
    rand.Read(b)
    return base64.StdEncoding.EncodeToString(b)
}
178 chars
11 lines

You can customize the length of the password by passing a different value to the n parameter in the RandomString() function. Additionally, you may remove slash / and plus + symbols from the resulting string if your use case does not accept them:

main.go
import (
    "crypto/rand"
    "encoding/base64"
    "strings"
)

func RandomPassword(length int) string {
    b := make([]byte, length)
    _, err := rand.Read(b)
    if err != nil {
        panic(err)
    }
    str := base64.URLEncoding.EncodeToString(b)
    str = strings.Replace(str, "/", "", -1)
    str = strings.Replace(str, "+", "", -1)
    return str[:length]
}
371 chars
18 lines

This function produces a password with the specified length without special characters / and +.

gistlibby LogSnag