项目作者: cat-dealer

项目描述 :
A painless convenience wrapper around math/rand and crypto/rand
高级语言: Go
项目地址: git://github.com/cat-dealer/go-rand.git
创建时间: 2019-12-30T22:38:36Z
项目社区:https://github.com/cat-dealer/go-rand

开源协议:The Unlicense

下载


go-rand

A painless convenience wrapper around math/rand and crypto/rand

Installation: go get github.com/cat-dealer/go-rand/v2

Full documentation: godoc

Examples

Pseudo-random

Generating pseudo-random integers, booleans and bytes

  1. bytes := rand.Bytes(16) // returns 16 bytes
  2. int := rand.Int(1, 3) // returns 1, 2 or 3
  3. bool := rand.Bool() // returns true or false

Strings and runes can only be generated from a predefined pool of allowed characters; you
can either provide your own pool:

str := rand.String(4, []rune{'a', 'b', 'c'}) // returns 4 random characters from the []rune slice

or use one of the built-in pools:

str := rand.String(4, rand.GetAlphanumericPool()) // returns 4 letters or numbers

Cryptographically random

Generating cryptographically secure random values isn’t any harder than generating pseudo-random ones:

  1. bytes, err := rand.SecureBytes(16) // returns 16 bytes
  2. int, err := rand.SecureInt(1, 3) // return 1, 2 or 3
  3. bool, err := rand.SecureBool() // returns true or false

Strings are just as easy:

str, err := rand.SecureString(4, rand.GetAlphanumericPool()) // returns 4 letters or numbers

Important note

This package may panic if called with impossible parameters (e.g. rand.Int(0, -1)) or using empty pool slices for rune/string generation!

Licensing

The Unlicense