package util import ( "crypto/md5" "fmt" "net/url" "strconv" "strings" ) func SplitIgnoreSpace(str string, sep string) []string { split := strings.Split(str, sep) result := make([]string, 0, len(split)) for _, elem := range split { value := strings.TrimSpace(elem) if value == "" { continue } result = append(result, value) } return result } func JoinIgnoreSpace(str []string, sep string) string { if str == nil || len(str) == 0 { return "" } builder := strings.Builder{} for index, elem := range str { if elem == "" { continue } builder.WriteString(elem) if index != len(str)-1 { // not latest index builder.WriteString(sep) } } return builder.String() } func ToString(value interface{}) string { switch v := value.(type) { case string: return v case uint8, uint16, uint32, uint64: convertUint64 := func(value interface{}) uint64 { switch v := value.(type) { case uint8: return uint64(v) case uint16: return uint64(v) case uint32: return uint64(v) case uint64: return v default: return 0 } } return strconv.FormatUint(convertUint64(value), 10) case int, int8, int16, int32, int64: convertInt64 := func(value interface{}) int64 { switch v := value.(type) { case int8: return int64(v) case int16: return int64(v) case int32: return int64(v) case int64: return v case int: return int64(v) default: return 0 } } return strconv.FormatInt(convertInt64(value), 10) case bool: if v { return "true" } return "false" // float 效率和直接fmt差距相差不大,为了保证不出问题,还是使用%v default: str, isOk := value.(fmt.Stringer) if isOk { return str.String() } return fmt.Sprintf("%+v", value) } } // 解码失败则返回原数据 func UrlDecode(str string) string { oldStr := str str, err := url.QueryUnescape(str) if err != nil { return oldStr } return str } // 编码url func UrlEncode(str string) string { return url.QueryEscape(str) } func String2Md5(str string) string { data := []byte(str) has := md5.Sum(data) md5str := fmt.Sprintf("%x", has) return md5str }