- add convert any type to ToStringMapE
This commit is contained in:
parent
c01685bb84
commit
d0ef62fd94
@ -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
|
||||
|
11
caste.go
11
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
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user