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
+19.7k Golang : Count JSON objects and convert to slice/array
+28.9k Golang : Get first few and last few characters from string
+17.7k Golang : Qt image viewer example
+22.6k Golang : Round float to precision example
+14.2k Golang : How to shuffle elements in array or slice?
+8k Android Studio : Rating bar example
+14.1k Golang : Convert IP version 6 address to integer or decimal number
+6.6k Golang : When to use make or new?
+18.5k Golang : Implement getters and setters
+4.6k Adding Skype actions such as call and chat into web page examples
+13.7k Golang : Convert spaces to tabs and back to spaces example
+29.7k Golang : Get and Set User-Agent examples