From a3dec9be9263a539860d33473bcf165044d414d4 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Mon, 18 Jul 2016 23:21:35 -0700 Subject: [PATCH] Module to get random string Signed-off-by: Vishal Rana --- random/random.go | 44 +++++++++++++++++++++++++++++++++++++++++++ random/random_test.go | 11 +++++++++++ 2 files changed, 55 insertions(+) create mode 100644 random/random.go create mode 100644 random/random_test.go diff --git a/random/random.go b/random/random.go new file mode 100644 index 0000000..ef87959 --- /dev/null +++ b/random/random.go @@ -0,0 +1,44 @@ +package random + +import ( + "math/rand" + "time" +) + +type ( + Random struct { + charset Charset + } + + Charset string +) + +const ( + Alphanumeric Charset = Alphabetic + Numeric + Alphabetic Charset = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + Numeric Charset = "0123456789" + Hex Charset = Numeric + "abcdef" +) + +var ( + global = New() +) + +func New() *Random { + rand.Seed(time.Now().UnixNano()) + return &Random{ + charset: Alphanumeric, + } +} + +func (r *Random) String(length uint8) string { + b := make([]byte, length) + for i := range b { + b[i] = r.charset[rand.Int63()%int64(len(r.charset))] + } + return string(b) +} + +func String(length uint8) string { + return global.String(length) +} diff --git a/random/random_test.go b/random/random_test.go new file mode 100644 index 0000000..b4cda50 --- /dev/null +++ b/random/random_test.go @@ -0,0 +1,11 @@ +package random + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test(t *testing.T) { + assert.Len(t, String(32), 32) +}