v0.0.435 add ConvertStructToMapOpt.MaxDepth
All checks were successful
Build Docker and Deploy / Run goext test-suite (push) Successful in 2m39s

This commit is contained in:
Mike Schwörer 2024-04-15 12:55:44 +02:00
parent f47e2a33fe
commit 8d52b41f57
Signed by: Mikescher
GPG Key ID: D3C7172E0A70F8CF
2 changed files with 13 additions and 8 deletions

View File

@ -1,5 +1,5 @@
package goext package goext
const GoextVersion = "0.0.434" const GoextVersion = "0.0.435"
const GoextVersionTimestamp = "2024-04-15T10:43:26+0200" const GoextVersionTimestamp = "2024-04-15T12:55:44+0200"

View File

@ -8,6 +8,7 @@ import (
type ConvertStructToMapOpt struct { type ConvertStructToMapOpt struct {
KeepJsonMarshalTypes bool KeepJsonMarshalTypes bool
MaxDepth *int
} }
func ConvertStructToMap(v any, opts ...ConvertStructToMapOpt) map[string]any { func ConvertStructToMap(v any, opts ...ConvertStructToMapOpt) map[string]any {
@ -16,7 +17,7 @@ func ConvertStructToMap(v any, opts ...ConvertStructToMapOpt) map[string]any {
opt = opts[0] opt = opts[0]
} }
res := reflectToMap(reflect.ValueOf(v), opt) res := reflectToMap(reflect.ValueOf(v), 1, opt)
if v, ok := res.(map[string]any); ok { if v, ok := res.(map[string]any); ok {
return v return v
@ -27,14 +28,18 @@ func ConvertStructToMap(v any, opts ...ConvertStructToMapOpt) map[string]any {
} }
} }
func reflectToMap(fv reflect.Value, opt ConvertStructToMapOpt) any { func reflectToMap(fv reflect.Value, depth int, opt ConvertStructToMapOpt) any {
if opt.MaxDepth != nil && depth > *opt.MaxDepth {
return fv.Interface()
}
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(), opt) return reflectToMap(fv.Elem(), depth, opt)
} }
} }
@ -51,7 +56,7 @@ func reflectToMap(fv reflect.Value, opt ConvertStructToMapOpt) 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), opt) arr[i] = reflectToMap(fv.Index(i), depth+1, opt)
} }
return arr return arr
@ -62,7 +67,7 @@ func reflectToMap(fv reflect.Value, opt ConvertStructToMapOpt) 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), opt) arr[i] = reflectToMap(fv.Index(i), depth+1, opt)
} }
return arr return arr
@ -85,7 +90,7 @@ func reflectToMap(fv reflect.Value, opt ConvertStructToMapOpt) 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), opt) res[fv.Type().Field(i).Name] = reflectToMap(fv.Field(i), depth+1, opt)
} }
} }