Bläddra i källkod

Added symbols for random string

Signed-off-by: Vishal Rana <vr@labstack.com>
Vishal Rana 8 år sedan
förälder
incheckning
9cedb429ff
2 ändrade filer med 20 tillägg och 24 borttagningar
  1. 18 22
      random/random.go
  2. 2 2
      random/random_test.go

+ 18 - 22
random/random.go

@@ -2,22 +2,24 @@ package random
 
 import (
 	"math/rand"
+	"strings"
 	"time"
 )
 
 type (
 	Random struct {
-		charset Charset
 	}
-
-	Charset string
 )
 
+// Charsets
 const (
-	Alphanumeric Charset = Alphabetic + Numeric
-	Alphabetic   Charset = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-	Numeric      Charset = "0123456789"
-	Hex          Charset = Numeric + "abcdef"
+	Uppercase    string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+	Lowercase           = "abcdefghijklmnopqrstuvwxyz"
+	Alphabetic          = Uppercase + Lowercase
+	Numeric             = "0123456789"
+	Alphanumeric        = Alphabetic + Numeric
+	Symbols             = "`" + `~!@#$%^&*()-_+={}[]|\;:"<>,./?`
+	Hex                 = Numeric + "abcdef"
 )
 
 var (
@@ -26,27 +28,21 @@ var (
 
 func New() *Random {
 	rand.Seed(time.Now().UnixNano())
-	return &Random{
-		charset: Alphanumeric,
-	}
-}
-
-func (r *Random) SetCharset(c Charset) {
-	r.charset = c
+	return new(Random)
 }
 
-func (r *Random) String(length uint8) string {
+func (r *Random) String(length uint8, charsets ...string) string {
+	charset := strings.Join(charsets, "")
+	if charset == "" {
+		charset = Alphanumeric
+	}
 	b := make([]byte, length)
 	for i := range b {
-		b[i] = r.charset[rand.Int63()%int64(len(r.charset))]
+		b[i] = charset[rand.Int63()%int64(len(charset))]
 	}
 	return string(b)
 }
 
-func SetCharset(c Charset) {
-	global.SetCharset(c)
-}
-
-func String(length uint8) string {
-	return global.String(length)
+func String(length uint8, charsets ...string) string {
+	return global.String(length, charsets...)
 }

+ 2 - 2
random/random_test.go

@@ -1,6 +1,7 @@
 package random
 
 import (
+	"regexp"
 	"testing"
 
 	"github.com/stretchr/testify/assert"
@@ -9,6 +10,5 @@ import (
 func Test(t *testing.T) {
 	assert.Len(t, String(32), 32)
 	r := New()
-	r.SetCharset(Numeric)
-	assert.Len(t, r.String(8), 8)
+	assert.Regexp(t, regexp.MustCompile("[0-9]+$"), r.String(8, Numeric))
 }