v0.0.435 add ConvertStructToMapOpt.MaxDepth
All checks were successful
Build Docker and Deploy / Run goext test-suite (push) Successful in 2m39s
All checks were successful
Build Docker and Deploy / Run goext test-suite (push) Successful in 2m39s
This commit is contained in:
parent
f47e2a33fe
commit
8d52b41f57
@ -1,5 +1,5 @@
|
||||
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"
|
||||
|
@ -8,6 +8,7 @@ import (
|
||||
|
||||
type ConvertStructToMapOpt struct {
|
||||
KeepJsonMarshalTypes bool
|
||||
MaxDepth *int
|
||||
}
|
||||
|
||||
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]
|
||||
}
|
||||
|
||||
res := reflectToMap(reflect.ValueOf(v), opt)
|
||||
res := reflectToMap(reflect.ValueOf(v), 1, opt)
|
||||
|
||||
if v, ok := res.(map[string]any); ok {
|
||||
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.IsNil() {
|
||||
return nil
|
||||
} 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()
|
||||
arr := make([]any, arrlen)
|
||||
for i := 0; i < arrlen; i++ {
|
||||
arr[i] = reflectToMap(fv.Index(i), opt)
|
||||
arr[i] = reflectToMap(fv.Index(i), depth+1, opt)
|
||||
}
|
||||
return arr
|
||||
|
||||
@ -62,7 +67,7 @@ func reflectToMap(fv reflect.Value, opt ConvertStructToMapOpt) any {
|
||||
arrlen := fv.Len()
|
||||
arr := make([]any, arrlen)
|
||||
for i := 0; i < arrlen; i++ {
|
||||
arr[i] = reflectToMap(fv.Index(i), opt)
|
||||
arr[i] = reflectToMap(fv.Index(i), depth+1, opt)
|
||||
}
|
||||
return arr
|
||||
|
||||
@ -85,7 +90,7 @@ func reflectToMap(fv reflect.Value, opt ConvertStructToMapOpt) any {
|
||||
|
||||
for i := 0; i < fv.NumField(); i++ {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user