feat: reflect添加struct转map的方法

main v1.0.3
NoahLan 1 year ago
parent 1bd773e3ac
commit e71d4898fc

@ -10,6 +10,37 @@ import (
"strconv" "strconv"
) )
type ConvertFn func(t reflect.Type, value reflect.Value) string
// StructToStrMap convert struct to string map, json tag
func StructToStrMap(v any, fn ConvertFn) map[string]string {
// 返回 key-value
ret := make(map[string]string)
rType := reflect.TypeOf(v)
rValue := reflect.ValueOf(v)
rValue = Indirect(rValue)
if rType.Kind() == reflect.Ptr {
rType = rType.Elem()
}
for i := 0; i < rType.NumField(); i++ {
rField := rType.Field(i)
jsonTag := rField.Tag.Get("json")
if jsonTag == "" || jsonTag == "-" {
continue
}
//rField.Type
if fn == nil {
fn = func(t reflect.Type, value reflect.Value) string {
return String(value)
}
}
ret[jsonTag] = fn(rField.Type, rValue.Field(i))
}
return ret
}
// BaseTypeVal convert custom type or intX,uintX,floatX to generic base type. // BaseTypeVal convert custom type or intX,uintX,floatX to generic base type.
// //
// intX/unitX => int64 // intX/unitX => int64

Loading…
Cancel
Save