From d0ef62fd9476a2cb80991ca232da31a550c7ef6a Mon Sep 17 00:00:00 2001 From: Sippakorn Raksakiart Date: Mon, 4 Nov 2019 19:10:43 +0700 Subject: [PATCH 1/2] - add convert any type to ToStringMapE --- cast_test.go | 9 +++++++-- caste.go | 11 ++++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/cast_test.go b/cast_test.go index d9a1479..7a50977 100644 --- a/cast_test.go +++ b/cast_test.go @@ -761,10 +761,14 @@ func TestToStringMapE(t *testing.T) { {map[string]interface{}{"tag": "tags", "group": "groups"}, map[string]interface{}{"tag": "tags", "group": "groups"}, false}, {`{"tag": "tags", "group": "groups"}`, map[string]interface{}{"tag": "tags", "group": "groups"}, false}, {`{"tag": "tags", "group": true}`, map[string]interface{}{"tag": "tags", "group": true}, false}, - + {struct { + Hello string + }{ + Hello: "World", + }, map[string]interface{}{"Hello": "World"}, false}, + {testing.T{}, map[string]interface{}{}, false}, // errors {nil, nil, true}, - {testing.T{}, nil, true}, {"", nil, true}, } @@ -772,6 +776,7 @@ func TestToStringMapE(t *testing.T) { errmsg := fmt.Sprintf("i = %d", i) // assert helper message v, err := ToStringMapE(test.input) + fmt.Printf("%+v", v) if test.iserr { assert.Error(t, err, errmsg) continue diff --git a/caste.go b/caste.go index a4859fb..a45eb4e 100644 --- a/caste.go +++ b/caste.go @@ -986,7 +986,16 @@ func ToStringMapE(i interface{}) (map[string]interface{}, error) { err := jsonStringToObject(v, &m) return m, err default: - return m, fmt.Errorf("unable to cast %#v of type %T to map[string]interface{}", i, i) + vo := reflect.ValueOf(i) + if vo.Kind() == reflect.Invalid { + return m, fmt.Errorf("unable to cast %#v of type %T to map[string]interface{}", i, i) + } + for i := 0; i < vo.NumField(); i++ { + if vo.Field(i).CanInterface() { + m[vo.Type().Field(i).Name] = vo.Field(i).Interface() + } + } + return m, nil } } From 64deafa3ae7bad85071ca2319039228ef1199835 Mon Sep 17 00:00:00 2001 From: Sippakorn Raksakiart Date: Mon, 4 Nov 2019 19:20:42 +0700 Subject: [PATCH 2/2] remove debuging code --- cast_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/cast_test.go b/cast_test.go index 7a50977..31cb5c8 100644 --- a/cast_test.go +++ b/cast_test.go @@ -776,7 +776,6 @@ func TestToStringMapE(t *testing.T) { errmsg := fmt.Sprintf("i = %d", i) // assert helper message v, err := ToStringMapE(test.input) - fmt.Printf("%+v", v) if test.iserr { assert.Error(t, err, errmsg) continue