rpc/protocol/json/util.go

47 lines
1.1 KiB
Go
Raw Normal View History

2018-03-20 06:31:54 +00:00
package json
import (
"fmt"
"reflect"
cur "git.loafle.net/commons_go/util/reflect"
2018-03-23 03:22:16 +00:00
jsoniter "github.com/json-iterator/go"
2018-03-20 06:31:54 +00:00
)
func convertParamsToStringArray(params []interface{}) ([]string, error) {
var values []string
if nil == params || 0 == len(params) {
return values, nil
}
for i, param := range params {
t := reflect.TypeOf(param)
switch t.Kind() {
case reflect.String:
values = append(values, param.(string))
case reflect.Array, reflect.Slice, reflect.Map, reflect.Struct:
2018-03-23 03:22:16 +00:00
b, err := jsoniter.Marshal(param)
2018-03-20 06:31:54 +00:00
if nil != err {
return nil, err
}
values = append(values, string(b))
case reflect.Ptr:
if t.Elem().Kind() != reflect.Struct {
return nil, fmt.Errorf("Pointer of param[%d] is permitted only Struct type", i)
}
2018-03-23 03:22:16 +00:00
b, err := jsoniter.Marshal(param)
2018-03-20 06:31:54 +00:00
if nil != err {
return nil, err
}
values = append(values, string(b))
default:
s, err := cur.ConvertToString(param)
if nil != err {
return nil, fmt.Errorf("String conversion of param[%d] has been failed [%v]", i, err)
}
values = append(values, s)
}
}
return values, nil
}