Skip to content

Commit

Permalink
gvalue MapToStruct
Browse files Browse the repository at this point in the history
  • Loading branch information
snail007 committed Jan 9, 2024
1 parent 7743cc0 commit a0ce778
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
7 changes: 7 additions & 0 deletions util/value/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -1184,6 +1184,10 @@ var typeOfBytes = reflect.TypeOf([]byte(nil))
// if 'mkey' not exists the filed name will used as map key, for example: User{} or new(User).
// Returned newStruct is a struct, for example: newStruct.(User) to assert it type.
// Details refer to TestMapToStruct.
// Ignore filed, set tag mkey:"-", for example:
// User{
// Age int `mkey:"-"`
// }
func MapToStruct(mapData map[string]interface{}, _value interface{}, tagName ...string) (newStruct interface{}, err error) {
if IsNil(_value) || (reflect.TypeOf(_value).Kind() != reflect.Struct &&
reflect.TypeOf(_value).Kind() != reflect.Ptr) {
Expand Down Expand Up @@ -1218,6 +1222,9 @@ func MapToStruct(mapData map[string]interface{}, _value interface{}, tagName ...
fieldKind = fieldType.Kind()
}
col := strings.Split(field.Tag.Get(tag), ",")[0]
if col == "-" {
continue
}
val, ok := mapData[col]
if !ok {
val, ok = mapData[field.Name]
Expand Down
6 changes: 5 additions & 1 deletion util/value/value_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,9 @@ type YourStruct struct {
ErrStructField YourInnerStruct
MapKey int8 `mkey:"key1"`
privateField int
MapField map[string]interface{} //map field only map[string]interface{} supported
//map field only map[string]interface{} supported
MapField map[string]interface{}
IgnoreField int `mkey:"-"`
}

type YourInnerStruct struct {
Expand Down Expand Up @@ -587,6 +589,7 @@ func TestMapToStruct(t *testing.T) {
"key1": int8(8),
"privateField": 1,
"MapField": map[string]string{"abc": "123"},
"IgnoreField": 1,
}

for _, v := range []interface{}{YourStruct{}, new(YourStruct)} {
Expand Down Expand Up @@ -618,6 +621,7 @@ func TestMapToStruct(t *testing.T) {
assert.Equal(t, "nested", yourStruct.PtrStructField.InnerStrField)
assert.Equal(t, 0, yourStruct.privateField)
assert.Equal(t, "123", yourStruct.MapField["abc"])
assert.Equal(t, 0, yourStruct.IgnoreField)
}
// 测试第二个参数是不同的结构体的情况
result, err := MapToStruct(mapData, YourSecondStruct{})
Expand Down

0 comments on commit a0ce778

Please sign in to comment.