Golang : Generate random string
In this tutorial, we will learn how to generate random string in Golang. Random strings can be used in many applications, such as generating random identifiers for job code, session id, secure token and many others.
package main
import (
"encoding/base64"
"crypto/rand"
"fmt"
)
func main() {
size := 32 // change the length of the generated random string here
rb := make([]byte,size)
_, err := rand.Read(rb)
if err != nil {
fmt.Println(err)
}
rs := base64.URLEncoding.EncodeToString(rb)
fmt.Println(rs)
}
Output :
>go run randomstr.go
k38b1e3c4YVQJ4FMrgcRBLU2DyEuDlyxVNjy3UA7sIw=
>go run randomstr.go
b6NW5LJY1gI5Hui7oWZbTJa_LCsL__JaJ33zZ5NIXHE=
In real world application, the above random string generation codes will be good for any practical use. The reason I put it there is to show you one way of generating random string.
It would be a good idea to write a function for generating random string(that is able to handle alphanumerica, alpha or numeric) and put the function in a package for easier calling. See randStr() function below :
package main
import (
"crypto/rand"
"fmt"
)
func randStr(strSize int, randType string) string {
var dictionary string
if randType == "alphanum" {
dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
}
if randType == "alpha" {
dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
}
if randType == "number" {
dictionary = "0123456789"
}
var bytes = make([]byte, strSize)
rand.Read(bytes)
for k, v := range bytes {
bytes[k] = dictionary[v%byte(len(dictionary))]
}
return string(bytes)
}
func main() {
fmt.Println("Alphanum : ", randStr(16, "alphanum"))
fmt.Println("Alpha : ", randStr(16, "alpha"))
fmt.Println("Numbers : ", randStr(16, "number"))
}
Output (sample) :
Alphanum : jem7veyr7VVi2gNT
Alpha : UYqbhKPACfHsvjLh
Numbers : 8892932200439488
Hope this tutorial can be useful to you.
See also : Golang : md5 hash of a string
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.7k Golang : Append and add item in slice
+13.7k Elastic Search : Mapping date format and sort by date
+8k Golang : Implementing class(object-oriented programming style)
+17.4k Golang : Login and logout a user after password verification and redirect example
+36k Golang : Display float in 2 decimal points and rounding up or down
+23.7k Golang : How to validate URL the right way
+6.6k Golang : Get Alexa ranking data example
+16k Golang : Execute terminal command to remote machine example
+10.2k Golang : Get local time and equivalent time in different time zone
+35.5k Golang : How to split or chunking a file to smaller pieces?
+8.2k Golang : Convert(cast) []byte to io.Reader type
+19.5k Golang : Convert seconds to human readable time format example