-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_utils.go
More file actions
70 lines (59 loc) · 1.79 KB
/
Copy pathstring_utils.go
File metadata and controls
70 lines (59 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package ezutil
import (
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"strconv"
"strings"
"unicode"
"github.com/google/uuid"
"github.com/itsLeonB/ungerr"
)
// Parse converts a string value to the specified type T.
// Supported types include string, int, bool, and uuid.UUID.
// Returns an error if parsing fails or the type is unsupported.
func Parse[T any](value string) (T, error) {
var parsed any
var err error
var zero T
switch any(zero).(type) {
case string:
return any(value).(T), nil
case int:
parsed, err = strconv.Atoi(value)
case bool:
parsed, err = strconv.ParseBool(value)
case uuid.UUID:
parsed, err = uuid.Parse(value)
default:
return zero, fmt.Errorf("unsupported type: %T", zero)
}
if err != nil {
return zero, ungerr.Wrapf(err, "failed to parse value '%s' as %T", value, zero)
}
return parsed.(T), nil
}
// GenerateRandomString creates a cryptographically secure random string of the specified length.
// The string is base64-encoded using URL-safe encoding without padding.
// Returns an error if length is non-positive or random generation fails.
func GenerateRandomString(length int) (string, error) {
if length <= 0 {
return "", ungerr.Unknown("length must be greater than 0")
}
randomBytes := make([]byte, length)
_, err := io.ReadFull(rand.Reader, randomBytes)
if err != nil {
return "", ungerr.Wrap(err, "failed to generate random string")
}
return base64.URLEncoding.EncodeToString(randomBytes), nil
}
// Capitalize converts the first character of a word to uppercase and the rest to lowercase.
// Returns an empty string if the input is empty.
// Useful for formatting names and titles consistently.
func Capitalize(word string) string {
if len(word) == 0 {
return ""
}
return string(unicode.ToUpper(rune(word[0]))) + strings.ToLower(word[1:])
}