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.6k Golang : Append content to a file
+9.6k Golang : Get current, epoch time and display by year, month and day
+6.3k PHP : Shuffle to display different content or advertisement
+11.8k Golang : Perform sanity checks on filename example
+11.9k Golang : convert(cast) string to integer value
+23.5k Golang : Fix type interface{} has no field or no methods and type assertions example
+8.6k Golang : Accept any number of function arguments with three dots(...)
+19.6k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+15.5k Golang : Get current time from the Internet time server(ntp) example
+86.2k Golang : How to convert character to ASCII and back
+8.8k Golang : Handle sub domain with Gin
+33.7k Golang : Call a function after some delay(time.Sleep and Tick)