diff --git a/util/crypto/aes/aes.go b/util/crypto/aes/aes.go index 21d4738..482b024 100644 --- a/util/crypto/aes/aes.go +++ b/util/crypto/aes/aes.go @@ -1,4 +1,4 @@ -package crypto +package aes import ( "bytes" diff --git a/util/reflect/reflect.go b/util/reflect/reflect.go index 43289eb..e65f2ee 100644 --- a/util/reflect/reflect.go +++ b/util/reflect/reflect.go @@ -138,6 +138,45 @@ func Set(hacky interface{}, field string, value interface{}) (err error) { return } switch fieldKind { + case reflect.Struct: + switch rv.Kind() { + case reflect.Map: + keys := rv.MapKeys() + subVal := reflect.New(refField.Type()) + for _, key := range keys { + pv := rv.MapIndex(key) + if key.Kind() == reflect.String { + if err = Set(subVal.Interface(), key.String(), pv.Interface()); err != nil { + return err + } + } + } + refField.Set(subVal.Elem()) + default: + err = fmt.Errorf("struct unsupported assign kind %s", rv.Kind()) + } + case reflect.Ptr: + elemType := refField.Type() + if elemType.Elem().Kind() == reflect.Struct { + switch rv.Kind() { + case reflect.Map: + keys := rv.MapKeys() + subVal := reflect.New(elemType.Elem()) + for _, key := range keys { + pv := rv.MapIndex(key) + if key.Kind() == reflect.String { + if err = Set(subVal.Interface(), key.String(), pv.Interface()); err != nil { + return err + } + } + } + refField.Set(subVal) + default: + err = fmt.Errorf("struct unsupported assign kind %s", rv.Kind()) + } + } else { + err = fmt.Errorf("ptr can't set kind %s", elemType.Elem().Kind()) + } case reflect.Array, reflect.Slice: innerType := refField.Type().Elem() if rv.Kind() == reflect.Array || rv.Kind() == reflect.Slice { diff --git a/util/reflection/reflection_test.go b/util/reflection/reflection_test.go index b1768e8..7a26aad 100644 --- a/util/reflection/reflection_test.go +++ b/util/reflection/reflection_test.go @@ -1,17 +1,31 @@ package reflection -import "testing" +import ( + "fmt" + "testing" +) +type Fakeb struct { + In int `json:"in"` +} type fake struct { - Name string `json:"name"` - Age int `json:"age"` + Name string `json:"name"` + Age int `json:"age"` + Usage *Fakeb `json:"usage"` } func TestSetter(t *testing.T) { dst := &fake{} - ms := map[string]string{"name": "aa", "age": "5"} - Setter(dst, ms) + ms := map[string]any{"name": "aa", "age": "5", "usage": map[string]any{"in": 15}} + err := Setter(dst, ms) + if err != nil { + t.Error(err) + return + } if dst.Age != 5 { t.Errorf("setter failed") + } else { + fmt.Println(dst.Usage.In) + fmt.Printf("%+v", dst) } }