作者 yangfu

radom string

package common
import (
"bytes"
"fmt"
"encoding/json"
"math/rand"
)
// Must panics if err is not nil.
... ... @@ -33,4 +35,17 @@ func AssertJson(object interface{})string{
return ""
}
return string(json)
}
var randomChars = "ABCDEFGHJKMNPQRSTWXYZabcdefhjkmnprstwxyz2345678" /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
func RandomString(l int)string{
if l<=0{
return ""
}
lenChars :=len(randomChars) -1
rsp :=bytes.NewBuffer(nil)
for i:=0;i<l;i++{
rsp.WriteByte(randomChars[rand.Intn(lenChars)])
}
return rsp.String()
}
\ No newline at end of file
... ...
package common
import (
"testing"
)
func Test_RandomString(t *testing.T){
input :=[]int{6,10,20,16,32}
for i:=range input{
l :=input[i]
out := RandomString(l)
if len(out)!=l{
t.Fatal("length not equal want :",l," out:",out)
}
}
}
func Benchmark_RandomString(b *testing.B) {
input :=[]int{10,20,16,32}
l :=0
out :=""
for i:=0;i<b.N;i++{
l=i%4
l=input[l]
out = RandomString(l)
if len(out)!=l{
b.Fatal("length not equal want :",l," out:",out)
}
}
}
\ No newline at end of file
... ...