Browse Source

Module to get random string

Signed-off-by: Vishal Rana <vr@labstack.com>
Vishal Rana 9 năm trước cách đây
mục cha
commit
a3dec9be92
2 tập tin đã thay đổi với 55 bổ sung0 xóa
  1. 44 0
      random/random.go
  2. 11 0
      random/random_test.go

+ 44 - 0
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)
+}

+ 11 - 0
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)
+}