103 lines
2.5 KiB
Go
103 lines
2.5 KiB
Go
package common
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
"unicode"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
|
)
|
|
|
|
// StructToMap2 对象转map,去掉无效值
|
|
func StructToMap2(u interface{}) []bson.M {
|
|
t := reflect.TypeOf(u)
|
|
v := reflect.ValueOf(u)
|
|
p := make([]bson.M, 0)
|
|
for i := 0; i < t.NumField(); i++ {
|
|
fv := v.Field(i).Type()
|
|
vv := v.Field(i)
|
|
k, _ := t.Field(i).Tag.Lookup("bson")
|
|
switch fv.Kind() {
|
|
case reflect.String:
|
|
if vv.String() != "" {
|
|
if k == "_id" {
|
|
idv, _ := primitive.ObjectIDFromHex(vv.String())
|
|
p = append(p, bson.M{"$match": bson.M{k: idv}})
|
|
} else {
|
|
p = append(p, bson.M{"$match": bson.M{k: vv.String()}})
|
|
}
|
|
fmt.Println(vv.String())
|
|
}
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
if vv.Int() != 0 {
|
|
p = append(p, bson.M{"$match": bson.M{k: vv.Interface()}})
|
|
}
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
|
if vv.Uint() != 0 {
|
|
p = append(p, bson.M{"$match": bson.M{k: vv.Interface()}})
|
|
}
|
|
case reflect.Interface, reflect.Ptr:
|
|
if vv.Uint() != 0 {
|
|
p = append(p, bson.M{"$match": bson.M{k: vv.Interface()}})
|
|
}
|
|
}
|
|
}
|
|
return p
|
|
}
|
|
|
|
// StructToMap 对象转map,去掉无效值
|
|
func StructToMap(u interface{}) (m map[string]interface{}) {
|
|
t := reflect.TypeOf(u)
|
|
v := reflect.ValueOf(u)
|
|
p := make(map[string]interface{})
|
|
for i := 0; i < t.NumField(); i++ {
|
|
fv := v.Field(i)
|
|
ft := t.Field(i)
|
|
jsonTag, _ := ft.Tag.Lookup("json")
|
|
switch fv.Kind() {
|
|
case reflect.String:
|
|
if fv.String() != "" {
|
|
p[jsonTag] = fv.Interface()
|
|
}
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
if fv.Int() != 0 {
|
|
p[jsonTag] = fv.Interface()
|
|
}
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
if fv.Uint() != 0 {
|
|
p[jsonTag] = fv.Interface()
|
|
}
|
|
case reflect.Float32, reflect.Float64:
|
|
if fv.Float() != 0 {
|
|
p[jsonTag] = fv.Interface()
|
|
}
|
|
default:
|
|
p[jsonTag] = fv.Interface()
|
|
|
|
}
|
|
}
|
|
return p
|
|
}
|
|
|
|
// Ucfirst () 字符串首字母大写
|
|
func Ucfirst(str string) string {
|
|
for i, v := range str {
|
|
return string(unicode.ToUpper(v)) + str[i+1:]
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// Lcfirst () 字符串首字母小写
|
|
func Lcfirst(str string) string {
|
|
for i, v := range str {
|
|
return string(unicode.ToLower(v)) + str[i+1:]
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// MobileBlurry ()
|
|
func MobileBlurry(str string) string {
|
|
return str[0:3] + "****" + str[7:]
|
|
}
|