Last active
July 5, 2019 07:49
-
-
Save xin053/18e6556062e0ea1070086623a1306f33 to your computer and use it in GitHub Desktop.
[go random]go random #go #random
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 更安全的随机 | |
package main | |
import ( | |
"crypto/rand" | |
// "encoding/base64" | |
// "encoding/hex" | |
"fmt" | |
) | |
// Key return a random key | |
func Key() string { | |
buf := make([]byte, 16) | |
_, err := rand.Read(buf) | |
if err != nil { | |
panic(err) // out of randomness, should never happen | |
} | |
return fmt.Sprintf("%x", buf) | |
// or hex.EncodeToString(buf) | |
// or base64.StdEncoding.EncodeToString(buf) | |
} | |
func main() { | |
fmt.Println(Key()) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
func main() { | |
// 必须要设置 Seed, 否则每次产生的随机数相同 | |
rand.Seed(time.Now().UnixNano()) | |
fmt.Println(rand.Int31n(100)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment