Files
servicebase/pkg/common/util/string_util.go
2025-11-18 17:48:20 +08:00

155 lines
3.1 KiB
Go

package util
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"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 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 interface{}) []byte {
b, _ := json.Marshal(source)
return b
}
func ToJsonString(source interface{}) string {
return string(ToJson(source))
}
func NowTimeToString() string {
return time.Now().Format(TimeLayout)
}
func NowTimeIncreaseString(t time.Duration) string {
return time.Now().Add(t).Format(TimeLayout)
}
func NowDateToString() string {
return time.Now().Format(DateLayout)
}
func NowDateToStringShort() string {
return time.Now().Format(DateLayoutShort)
}
func DateToString(source time.Time) string {
return source.Format(TimeLayout)
}
func Md5(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
func ProcessTimeStr(s string) (string, error) {
// 定义两种时间格式
layout1 := "2006-01-02 15:04:05" // 无时区的格式
layout2 := "2006-01-02 15:04:05 -0700 MST" // 带时区的格式(包含偏移和时区名称)
// 尝试解析为无时区格式
_, err1 := time.Parse(layout1, s)
if err1 == nil {
return s, nil // 直接返回原字符串
}
// 尝试解析为带时区格式
t2, err2 := time.Parse(layout2, s)
if err2 == nil {
// 格式化为无时区格式
return t2.Format(layout1), nil
}
// 两种格式都不匹配
return "", fmt.Errorf("invalid time format: %s", s)
}
// 解析url里的参数为map
func ParseUrlParameter(fullUrl string) (result map[string]string) {
result = make(map[string]string)
// 解析URL
parsedURL, err := url.Parse(fullUrl)
if err != nil {
fmt.Printf("解析URL失败: %v\n", err)
return
}
// 解析查询参数
queryParams := parsedURL.Query()
// 输出所有参数
for key, values := range queryParams {
result[key] = values[0]
}
return
}