Skip to content

Instantly share code, notes, and snippets.

@xin053
Last active July 5, 2019 07:49
Show Gist options
  • Save xin053/18e6556062e0ea1070086623a1306f33 to your computer and use it in GitHub Desktop.
Save xin053/18e6556062e0ea1070086623a1306f33 to your computer and use it in GitHub Desktop.
[go random]go random #go #random
// 更安全的随机
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())
}
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