feat: generate random string for ID usage
This commit is contained in:
parent
84cfab08ef
commit
9d9311e90c
|
@ -0,0 +1,21 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
// RandomString generates a random string with p bytes of length.
|
||||
// Specifying 10 in the p parameter will result in the length of 20.
|
||||
func RandomString(p int) (string, error) {
|
||||
if p <= 0 {
|
||||
p = 10
|
||||
}
|
||||
arr := make([]byte, p)
|
||||
_, err := rand.Read(arr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hex.EncodeToString(arr), nil
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package utils_test
|
||||
|
||||
import (
|
||||
"jokes-bapak2-api/app/v1/utils"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRandomString(t *testing.T) {
|
||||
t.Run("should create a random string with param", func(t *testing.T) {
|
||||
random, err := utils.RandomString(10)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if len(random) != 20 {
|
||||
t.Error("result is not within the length of 10")
|
||||
}
|
||||
})
|
||||
t.Run("should create a random string with invalid params", func(t *testing.T) {
|
||||
random, err := utils.RandomString(10)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if len(random) != 20 {
|
||||
t.Error("result is not within the length of 10")
|
||||
}
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue