Files
servicebase/pkg/helper/string_util.go
2025-11-19 14:24:13 +08:00

145 lines
2.9 KiB
Go

package helper
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
const (
PhotoDomainUrl = "https://photo-app.ddegame.cn/"
TimeLayout = "2006-01-02 15:04:05"
DateLayout = "2006-01-02"
DateLayoutShort = "20060102"
)
func FullPhotoUrl(path string) string {
if len(path) == 0 {
return ""
}
if strings.Index(path, "http") == 0 {
return path
}
return PhotoDomainUrl + path
}
func Md5ForList(s ...string) string {
sort.Strings(s)
h := md5.New()
h.Write([]byte(strings.Join(s, "")))
return hex.EncodeToString(h.Sum(nil))
}
func StringToInt(source string) int {
target, _ := strconv.Atoi(source)
return target
}
func StringToInt64(source string) int64 {
target, _ := strconv.Atoi(source)
return int64(target)
}
func StringToFloat(source string) float64 {
target, _ := strconv.ParseFloat(source, 64)
return target
}
func StringIntPlus(s1, s2 string) string {
return strconv.Itoa(StringToInt(s1) + StringToInt(s2))
}
func StringIntMultiply(s1, s2 string) string {
return strconv.Itoa(StringToInt(s1) * StringToInt(s2))
}
func StringIntSub(s1, s2 string) string {
return strconv.Itoa(StringToInt(s1) - StringToInt(s2))
}
func StringFloatSub(s1, s2 string) string {
return strconv.FormatFloat(StringToFloat(s1)-StringToFloat(s2), 'f', -1, 64)
}
func ListToSet(list []string) (set []string) {
m := make(map[string]bool, 0)
for i := range list {
m[list[i]] = true
}
for k := range m {
set = append(set, k)
}
return
}
func ToJson(source any) []byte {
b, _ := json.Marshal(source)
return b
}
func NowTimeToString() string {
return time.Now().Format(TimeLayout)
}
func NowTimeIncreaseString(t time.Duration) string {
now := time.Now()
now.Add(t)
return now.Format(TimeLayout)
}
func NowDateToString() string {
return time.Now().Format(DateLayout)
}
func NowDateToStringShort() string {
return time.Now().Format(DateLayoutShort)
}
func Md5(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
func ZeroFillByStr(str string, resultLen int, reverse bool) string {
if len(str) > resultLen || resultLen <= 0 {
return str
}
if reverse {
return fmt.Sprintf("%0*s", resultLen, str) //不足前置补零
}
result := str
for i := 0; i < resultLen-len(str); i++ {
result += "0"
}
return result
}
func IsMobile(no string) bool {
return regexp.MustCompile("^1[3456789]\\d{9}$").MatchString(no)
}
func IsEmail(email string) bool {
pattern := `^[0-9a-z][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}[0-9a-z]\.){1,4}[a-z]{2,4}$`
return regexp.MustCompile(pattern).MatchString(email)
}
func LegalUsername(source string) bool {
return regexp.MustCompile("^\\D[\\w-]{5,17}$").MatchString(source)
}
func LegalShortUsername(source string) bool {
return regexp.MustCompile("^[a-zA-Z][\\w-]{2,17}$").MatchString(source)
}
func LegalPassword(source string) bool {
return regexp.MustCompile("^[a-zA-Z0-9,.!@#$%^&*()_-]{6,18}$").MatchString(source)
}