Creating random string in Go

Recently as I was writing code for one of the project, I had the need for Generating a Randome String of certain length. This is second time I encountered this and had to lookup how to do this.

I am sharing the code snippet as a reference to myself and anyone else who might look for this information.


//This function generates random string 
func GenerateRandomString(n int) (string, error) {
    b := make([]byte, n)
    _, err := rand.Read(b)

    // Note that err == nil only if we read len(b) bytes.
    if err != nil {
        return "", err
    }
    return base64.URLEncoding.EncodeToString(b), err
}

No Comments Yet