generate a random string in go

To generate a random string in Go, we can use the crypto/rand package. Here's an example code that generates a random string of length n:

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

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

In the above code, we're creating a byte slice of length n using the make function. Then we're using the rand.Read function to fill this slice with random bytes generated by the crypto/rand package. Finally, we're encoding this byte slice as a URL-safe base64 string using the base64.URLEncoding.EncodeToString function and returning it.

To generate a random string of length 10, we can call the randomString function like this:

main.go
fmt.Println(randomString(10))
30 chars
2 lines

gistlibby LogSnag