feat: generate random string for ID usage

This commit is contained in:
Reinaldy Rafli 2021-08-04 01:15:35 +07:00
parent 84cfab08ef
commit 9d9311e90c
4 changed files with 50 additions and 2 deletions

View File

@ -8,4 +8,4 @@ func IsIn(arr []string, value string) bool {
}
}
return false
}
}

View File

@ -20,4 +20,4 @@ func TestIsIn(t *testing.T) {
t.Error("check should be false: ", check)
}
})
}
}

View File

@ -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
}

View File

@ -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")
}
})
}