提交
This commit is contained in:
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package randomx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"math/rand"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 生成指定位数的随机字符串
|
||||||
|
func RandomStr(length int) (string, error) {
|
||||||
|
if length <= 0 {
|
||||||
|
return "", errors.New("位数必须大于0")
|
||||||
|
}
|
||||||
|
str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ黄新云"
|
||||||
|
bytes := []rune(str)
|
||||||
|
|
||||||
|
// 初始化参数,并赋予空间
|
||||||
|
var result = make([]rune, 0, length)
|
||||||
|
|
||||||
|
// 初始化随机因子
|
||||||
|
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||||
|
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
|
result = append(result, bytes[r.Intn(len(bytes))])
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(result), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成指定空间的随机数
|
||||||
|
func RandomInt(min, max int) (int, error) {
|
||||||
|
c := max - min
|
||||||
|
if c <= 0 {
|
||||||
|
return 0, errors.New("max值需要大于min")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化随机因子
|
||||||
|
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||||
|
|
||||||
|
res := r.Intn(c)
|
||||||
|
|
||||||
|
return min + res, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package randomx_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"code.yun.ink/pkg/randomx"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRandomInt(t *testing.T) {
|
||||||
|
i, err := randomx.RandomInt(100, 101)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err.Error())
|
||||||
|
}
|
||||||
|
if i >= 100 && i <= 101 {
|
||||||
|
t.Log("正常")
|
||||||
|
} else {
|
||||||
|
t.Fatal("不正常", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRandomStr(t *testing.T) {
|
||||||
|
str, err := randomx.RandomStr(10)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err.Error())
|
||||||
|
}
|
||||||
|
if len(str) == 10 {
|
||||||
|
t.Log("正常")
|
||||||
|
} else {
|
||||||
|
t.Fatal("不正常", str)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user