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.6k Swift : Convert (cast) String to Double
+25.6k Golang : How to read integer value from standard input ?
+8k Golang : Find relative luminance or color brightness
+11k Golang : How to pipe input data to executing child process?
+13.5k Golang : Check if an integer is negative or positive
+7.5k Golang : get the current working directory of a running program
+8.9k Golang : Gonum standard normal random numbers example
+5.8k AWS S3 : Prevent Hotlinking policy
+4.2k Linux/MacOSX : Search and delete files by extension
+6k Golang : Scan forex opportunities by Bollinger bands
+16.6k Golang : Set up source IP address before making HTTP request
+7.6k Golang : Generate human readable password