✨ Add Random Generator
This commit is contained in:
parent
5c1132e414
commit
1677a692d1
8 changed files with 142 additions and 53 deletions
60
gen_rand.go
Normal file
60
gen_rand.go
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
package nomino
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"strings"
|
||||
|
||||
"github.com/deatil/go-encoding/base62"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func uuidGen(*Config) (string, error) {
|
||||
u, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
// UUID generates a UUIDv4.
|
||||
func UUID() Generator {
|
||||
return uuidGen
|
||||
}
|
||||
|
||||
type randConf struct {
|
||||
length int
|
||||
}
|
||||
|
||||
// RandomOption is an option for the Random Generator
|
||||
type RandomOption func(*randConf)
|
||||
|
||||
// RandomLength controls the length of the string generated by Random
|
||||
func RandomLength(length int) RandomOption {
|
||||
return func(c *randConf) {
|
||||
c.length = length
|
||||
}
|
||||
}
|
||||
|
||||
func getRandomBytes(l int) []byte {
|
||||
key := make([]byte, l)
|
||||
rand.Read(key)
|
||||
e := base62.StdEncoding.Encode(key)
|
||||
return e[:l]
|
||||
}
|
||||
|
||||
// Random generates a random string containing the characters [A-Za-z0-9].
|
||||
// By default, it will be eight characters long.
|
||||
func Random(opts ...RandomOption) Generator {
|
||||
c := randConf{8}
|
||||
for _, opt := range opts {
|
||||
opt(&c)
|
||||
}
|
||||
return func(*Config) (string, error) {
|
||||
var buff strings.Builder
|
||||
buff.Grow(c.length)
|
||||
for buff.Len() < c.length {
|
||||
buff.Write(getRandomBytes(c.length - buff.Len()))
|
||||
}
|
||||
return buff.String(), nil
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue