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

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