Skip to content

Commit

Permalink
add MustGenerateID function
Browse files Browse the repository at this point in the history
  • Loading branch information
jooola committed Jan 21, 2025
1 parent 993bf6a commit 527b83e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
18 changes: 13 additions & 5 deletions hcloud/exp/kit/randutil/id.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,21 @@ import (

// GenerateID returns a hex encoded random string with a len of 8 chars similar to
// "2873fce7".
//
// This function panics if [rand.Read] returns an error.
func GenerateID() string {
func GenerateID() (string, error) {
b := make([]byte, 4)
_, err := rand.Read(b)
if err != nil {
panic(fmt.Errorf("failed to generate random string: %w", err))
return "", fmt.Errorf("failed to generate random string: %w", err)
}
return hex.EncodeToString(b)
return hex.EncodeToString(b), nil
}

// MustGenerateID returns the result of [GenerateID], and panics if [rand.Read] returns
// an error.
func MustGenerateID() string {
result, err := GenerateID()
if err != nil {
panic(err)
}
return result
}
4 changes: 2 additions & 2 deletions hcloud/exp/kit/randutil/id_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import (
)

func TestGenerateRandomID(t *testing.T) {
found1 := GenerateID()
found2 := GenerateID()
found1 := MustGenerateID()
found2 := MustGenerateID()

assert.Len(t, found1, 8)
assert.Len(t, found2, 8)
Expand Down

0 comments on commit 527b83e

Please sign in to comment.