Skip to content

Commit

Permalink
Module to get random string
Browse files Browse the repository at this point in the history
Signed-off-by: Vishal Rana <[email protected]>
  • Loading branch information
vishr committed Jul 19, 2016
1 parent 722aa12 commit a3dec9b
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
44 changes: 44 additions & 0 deletions random/random.go
Original file line number Diff line number Diff line change
@@ -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 changes: 11 additions & 0 deletions random/random_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package random

import (
"testing"

"github.com/stretchr/testify/assert"
)

func Test(t *testing.T) {
assert.Len(t, String(32), 32)
}

0 comments on commit a3dec9b

Please sign in to comment.