Skip to content

Commit 9cedb42

Browse files
committed
Added symbols for random string
Signed-off-by: Vishal Rana <vr@labstack.com>
1 parent e8995fb commit 9cedb42

File tree

2 files changed

+20
-24
lines changed

2 files changed

+20
-24
lines changed

random/random.go

+18-22
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,24 @@ package random
22

33
import (
44
"math/rand"
5+
"strings"
56
"time"
67
)
78

89
type (
910
Random struct {
10-
charset Charset
1111
}
12-
13-
Charset string
1412
)
1513

14+
// Charsets
1615
const (
17-
Alphanumeric Charset = Alphabetic + Numeric
18-
Alphabetic Charset = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
19-
Numeric Charset = "0123456789"
20-
Hex Charset = Numeric + "abcdef"
16+
Uppercase string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
17+
Lowercase = "abcdefghijklmnopqrstuvwxyz"
18+
Alphabetic = Uppercase + Lowercase
19+
Numeric = "0123456789"
20+
Alphanumeric = Alphabetic + Numeric
21+
Symbols = "`" + `~!@#$%^&*()-_+={}[]|\;:"<>,./?`
22+
Hex = Numeric + "abcdef"
2123
)
2224

2325
var (
@@ -26,27 +28,21 @@ var (
2628

2729
func New() *Random {
2830
rand.Seed(time.Now().UnixNano())
29-
return &Random{
30-
charset: Alphanumeric,
31-
}
32-
}
33-
34-
func (r *Random) SetCharset(c Charset) {
35-
r.charset = c
31+
return new(Random)
3632
}
3733

38-
func (r *Random) String(length uint8) string {
34+
func (r *Random) String(length uint8, charsets ...string) string {
35+
charset := strings.Join(charsets, "")
36+
if charset == "" {
37+
charset = Alphanumeric
38+
}
3939
b := make([]byte, length)
4040
for i := range b {
41-
b[i] = r.charset[rand.Int63()%int64(len(r.charset))]
41+
b[i] = charset[rand.Int63()%int64(len(charset))]
4242
}
4343
return string(b)
4444
}
4545

46-
func SetCharset(c Charset) {
47-
global.SetCharset(c)
48-
}
49-
50-
func String(length uint8) string {
51-
return global.String(length)
46+
func String(length uint8, charsets ...string) string {
47+
return global.String(length, charsets...)
5248
}

random/random_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package random
22

33
import (
4+
"regexp"
45
"testing"
56

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

0 commit comments

Comments
 (0)