diff --git a/api/app/v1/utils/array.go b/api/app/v1/utils/array.go index 6b70eaa..ba953b1 100644 --- a/api/app/v1/utils/array.go +++ b/api/app/v1/utils/array.go @@ -8,4 +8,4 @@ func IsIn(arr []string, value string) bool { } } return false -} \ No newline at end of file +} diff --git a/api/app/v1/utils/array_test.go b/api/app/v1/utils/array_test.go index 3868a40..506932c 100644 --- a/api/app/v1/utils/array_test.go +++ b/api/app/v1/utils/array_test.go @@ -20,4 +20,4 @@ func TestIsIn(t *testing.T) { t.Error("check should be false: ", check) } }) -} \ No newline at end of file +} diff --git a/api/app/v1/utils/random.go b/api/app/v1/utils/random.go new file mode 100644 index 0000000..374870b --- /dev/null +++ b/api/app/v1/utils/random.go @@ -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 +} diff --git a/api/app/v1/utils/random_test.go b/api/app/v1/utils/random_test.go new file mode 100644 index 0000000..8e62792 --- /dev/null +++ b/api/app/v1/utils/random_test.go @@ -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") + } + }) +}