From c52f7b6050e5520efb11c11a64e0bf75edd79618 Mon Sep 17 00:00:00 2001 From: Tai Groot Date: Mon, 13 Jun 2022 02:35:45 -0700 Subject: [PATCH] simplify random string generator --- utils.go | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/utils.go b/utils.go index d5fb2b8..9051387 100644 --- a/utils.go +++ b/utils.go @@ -2,18 +2,15 @@ package main import ( "crypto/rand" + "encoding/base64" ) -const ( - alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" -) - -// RandomString ... +// RandomString generates random bytes and then encodes them using base64 +// which guarantees they are URL-safe. The resultant output is not necessarily +// a valid base-64 string. func RandomString(length int) string { - bytes := make([]byte, length) + bytes := make([]byte, length*2) rand.Read(bytes) - for i, b := range bytes { - bytes[i] = alphabet[b%byte(len(alphabet))] - } - return string(bytes) + se := base64.StdEncoding.EncodeToString(bytes) + return se[0:length] }