2017-02-18 23:00:46 +01:00
|
|
|
package random
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/rand"
|
2017-06-06 00:01:05 +02:00
|
|
|
"strings"
|
2017-02-18 23:00:46 +01:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
Random struct {
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2017-06-06 00:01:05 +02:00
|
|
|
// Charsets
|
2017-02-18 23:00:46 +01:00
|
|
|
const (
|
2019-01-31 17:06:36 +01:00
|
|
|
Uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
|
|
Lowercase = "abcdefghijklmnopqrstuvwxyz"
|
|
|
|
Alphabetic = Uppercase + Lowercase
|
|
|
|
Numeric = "0123456789"
|
|
|
|
Alphanumeric = Alphabetic + Numeric
|
|
|
|
Symbols = "`" + `~!@#$%^&*()-_+={}[]|\;:"<>,./?`
|
|
|
|
Hex = Numeric + "abcdef"
|
2017-02-18 23:00:46 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
global = New()
|
|
|
|
)
|
|
|
|
|
|
|
|
func New() *Random {
|
|
|
|
rand.Seed(time.Now().UnixNano())
|
2017-06-06 00:01:05 +02:00
|
|
|
return new(Random)
|
2017-02-18 23:00:46 +01:00
|
|
|
}
|
|
|
|
|
2017-06-06 00:01:05 +02:00
|
|
|
func (r *Random) String(length uint8, charsets ...string) string {
|
|
|
|
charset := strings.Join(charsets, "")
|
|
|
|
if charset == "" {
|
|
|
|
charset = Alphanumeric
|
|
|
|
}
|
2017-02-18 23:00:46 +01:00
|
|
|
b := make([]byte, length)
|
|
|
|
for i := range b {
|
2017-06-06 00:01:05 +02:00
|
|
|
b[i] = charset[rand.Int63()%int64(len(charset))]
|
2017-02-18 23:00:46 +01:00
|
|
|
}
|
|
|
|
return string(b)
|
|
|
|
}
|
|
|
|
|
2017-06-06 00:01:05 +02:00
|
|
|
func String(length uint8, charsets ...string) string {
|
|
|
|
return global.String(length, charsets...)
|
2017-02-18 23:00:46 +01:00
|
|
|
}
|