goext/reflectext/convertToMap.go

73 lines
1013 B
Go
Raw Permalink Normal View History

2024-01-23 17:51:52 +01:00
package reflectext
import "reflect"
func ConvertStructToMap(v any) any {
return reflectToMap(reflect.ValueOf(v))
}
func reflectToMap(fv reflect.Value) any {
if fv.Kind() == reflect.Ptr {
if fv.IsNil() {
return nil
} else {
return reflectToMap(fv.Elem())
}
}
if fv.Kind() == reflect.Func {
// skip
return nil
}
if fv.Kind() == reflect.Array {
arrlen := fv.Len()
arr := make([]any, arrlen)
for i := 0; i < arrlen; i++ {
arr[i] = reflectToMap(fv.Index(i))
}
return arr
}
if fv.Kind() == reflect.Slice {
arrlen := fv.Len()
arr := make([]any, arrlen)
for i := 0; i < arrlen; i++ {
arr[i] = reflectToMap(fv.Index(i))
}
return arr
}
if fv.Kind() == reflect.Chan {
// skip
return nil
}
if fv.Kind() == reflect.Struct {
res := make(map[string]any)
for i := 0; i < fv.NumField(); i++ {
if fv.Type().Field(i).IsExported() {
res[fv.Type().Field(i).Name] = reflectToMap(fv.Field(i))
}
}
return res
}
return fv.Interface()
}