Using rand.Read method
func
GenerateRandomString(length int) string {
tempBytes := make([]byte, length)
_, err := rand.Read(tempBytes)
if err != nil {
fmt.Println("Error:
", err)
return ""
}
return fmt.Sprintf("%X",
tempBytes)
}
App.go
package main import ( "crypto/rand" "fmt" ) func GenerateRandomString(length int) string { tempBytes := make([]byte, length) _, err := rand.Read(tempBytes) if err != nil { fmt.Println("Error: ", err) return "" } return fmt.Sprintf("%X", tempBytes) } func main() { randStr1 := GenerateRandomString(10) randStr2 := GenerateRandomString(20) randStr3 := GenerateRandomString(30) fmt.Printf("randStr1 : %v\n", randStr1) fmt.Printf("randStr2 : %v\n", randStr2) fmt.Printf("randStr3 : %v\n", randStr3) }
Sample Output
randStr1 :
282A0A932F3609E87107
randStr2 :
35835506E0EC0F27E483156A5AB044FA79B33686
randStr3 :
1B0ACE0CE978FFE71DFF999B1953FEE627464682128AC54DF7A322E80C58
No comments:
Post a Comment