21
0
Fork 0

v0.0.416
Build Docker and Deploy / Run goext test-suite (push) Failing after 1m43s Details

This commit is contained in:
Mike Schwörer 2024-03-18 11:19:01 +01:00
parent dcd106c1cd
commit 14f39a9162
Signed by: Mikescher
GPG Key ID: D3C7172E0A70F8CF
2 changed files with 25 additions and 10 deletions

View File

@ -1,5 +1,5 @@
package goext
const GoextVersion = "0.0.415"
const GoextVersion = "0.0.416"
const GoextVersionTimestamp = "2024-03-18T10:42:00+0100"
const GoextVersionTimestamp = "2024-03-18T11:19:01+0100"

View File

@ -1,19 +1,30 @@
package reflectext
import "reflect"
import (
"encoding/json"
"reflect"
)
func ConvertStructToMap(v any) any {
return reflectToMap(reflect.ValueOf(v))
type ConvertStructToMapOpt struct {
KeepJsonMarshalTypes bool
}
func reflectToMap(fv reflect.Value) any {
func ConvertStructToMap(v any, opts ...ConvertStructToMapOpt) any {
opt := ConvertStructToMapOpt{}
if len(opts) > 0 {
opt = opts[0]
}
return reflectToMap(reflect.ValueOf(v), opt)
}
func reflectToMap(fv reflect.Value, opt ConvertStructToMapOpt) any {
if fv.Kind() == reflect.Ptr {
if fv.IsNil() {
return nil
} else {
return reflectToMap(fv.Elem())
return reflectToMap(fv.Elem(), opt)
}
}
@ -30,7 +41,7 @@ func reflectToMap(fv reflect.Value) any {
arrlen := fv.Len()
arr := make([]any, arrlen)
for i := 0; i < arrlen; i++ {
arr[i] = reflectToMap(fv.Index(i))
arr[i] = reflectToMap(fv.Index(i), opt)
}
return arr
@ -41,7 +52,7 @@ func reflectToMap(fv reflect.Value) any {
arrlen := fv.Len()
arr := make([]any, arrlen)
for i := 0; i < arrlen; i++ {
arr[i] = reflectToMap(fv.Index(i))
arr[i] = reflectToMap(fv.Index(i), opt)
}
return arr
@ -56,11 +67,15 @@ func reflectToMap(fv reflect.Value) any {
if fv.Kind() == reflect.Struct {
if opt.KeepJsonMarshalTypes && fv.Type().Implements(reflect.TypeFor[json.Marshaler]()) {
return fv.Interface()
}
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))
res[fv.Type().Field(i).Name] = reflectToMap(fv.Field(i), opt)
}
}