package util import ( "crypto/md5" "encoding/json" "fmt" "io" "reflect" "service/library/logger" "strings" "github.com/qiniu/qmgo" ) func ToJson(v any) string { str, err := json.Marshal(v) if err != nil { logger.Info("%v marsha failed, err: %v", v, err) } return string(str) } func StringToMd5(s string) string { m := md5.New() _, _ = io.WriteString(m, s) return fmt.Sprintf("%x", m.Sum(nil)) } // 将实体类结构体指针转为bson.M,采用反射 func EntityToM(p any) qmgo.M { set := qmgo.M{} pType := reflect.TypeOf(p).Elem() pVal := reflect.ValueOf(p).Elem() for i := 0; i < pType.NumField(); i++ { name := pType.Field(i).Tag.Get("bson") field := pVal.Field(i) if name != "_id" && !field.IsNil() { value := field.Elem().Interface() set[name] = value } } return set } func StringsContains(elems []string, v string) bool { for _, s := range elems { if s == v { return true } } return false } // 下划线转大写驼峰 func UderscoreToUpperCamelCase(s string) string { s = strings.Replace(s, "_", " ", -1) s = strings.Title(s) return strings.Replace(s, " ", "", -1) } // 数组转sql数组 []int{1, 2, 3) --> 1,2,3 func Convert2SqlArr(a ...any) string { return strings.Replace(strings.Trim(fmt.Sprint(a), "[]"), " ", ",", -1) }