nomino/gen_rand.go
2025-03-15 15:36:43 -05:00

60 lines
1.2 KiB
Go

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
}
}