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
+11.8k Golang : Get remaining text such as id or filename after last segment in URL path
+14.9k Golang : Get timezone offset from date or timestamp
+13.4k Golang : Tutorial on loading GOB and PEM files
+14.7k Golang : package is not in GOROOT during compilation
+19.8k Golang : How to get struct tag and use field name to retrieve data?
+5.2k Golang : fmt.Println prints out empty data from struct
+31.8k Golang : Math pow(the power of x^y) example
+14.3k Golang : Get URI segments by number and assign as variable example
+7.9k Golang : Metaprogramming example of wrapping a function
+20.7k Golang : How to force compile or remove object files first before rebuild?
+12k Golang : Get month name from date example
+7.1k Golang : Scanf function weird error in Windows