2023-07-06 17:53:38 +03:00
|
|
|
package util
|
2022-02-03 10:32:03 +03:00
|
|
|
|
|
|
|
import (
|
2023-02-19 04:50:30 +03:00
|
|
|
"crypto/rand"
|
|
|
|
"math/big"
|
2022-08-20 16:03:15 +03:00
|
|
|
"net/mail"
|
2023-08-04 16:55:07 +03:00
|
|
|
"strconv"
|
2022-02-03 10:32:03 +03:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
)
|
|
|
|
|
2023-08-04 16:55:07 +03:00
|
|
|
// ConvertStringToInt32 converts a string to int32.
|
|
|
|
func ConvertStringToInt32(src string) (int32, error) {
|
2023-10-28 04:04:32 +03:00
|
|
|
parsed, err := strconv.ParseInt(src, 10, 32)
|
2023-08-04 16:55:07 +03:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2023-10-28 04:04:32 +03:00
|
|
|
return int32(parsed), nil
|
2023-08-04 16:55:07 +03:00
|
|
|
}
|
|
|
|
|
2022-02-03 10:32:03 +03:00
|
|
|
// HasPrefixes returns true if the string s has any of the given prefixes.
|
|
|
|
func HasPrefixes(src string, prefixes ...string) bool {
|
|
|
|
for _, prefix := range prefixes {
|
|
|
|
if strings.HasPrefix(src, prefix) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2022-08-20 16:03:15 +03:00
|
|
|
// ValidateEmail validates the email.
|
|
|
|
func ValidateEmail(email string) bool {
|
|
|
|
if _, err := mail.ParseAddress(email); err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-02-03 10:32:03 +03:00
|
|
|
func GenUUID() string {
|
|
|
|
return uuid.New().String()
|
|
|
|
}
|
2022-10-27 17:02:42 +03:00
|
|
|
|
|
|
|
func Min(x, y int) int {
|
|
|
|
if x < y {
|
|
|
|
return x
|
|
|
|
}
|
|
|
|
return y
|
|
|
|
}
|
2023-02-19 04:50:30 +03:00
|
|
|
|
|
|
|
var letters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
|
|
|
|
|
|
|
// RandomString returns a random string with length n.
|
|
|
|
func RandomString(n int) (string, error) {
|
|
|
|
var sb strings.Builder
|
|
|
|
sb.Grow(n)
|
|
|
|
for i := 0; i < n; i++ {
|
|
|
|
// The reason for using crypto/rand instead of math/rand is that
|
|
|
|
// the former relies on hardware to generate random numbers and
|
|
|
|
// thus has a stronger source of random numbers.
|
|
|
|
randNum, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if _, err := sb.WriteRune(letters[randNum.Uint64()]); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return sb.String(), nil
|
|
|
|
}
|