rpc-go/protocol/json/util.go
2018-08-22 18:04:25 +09:00

47 lines
1.1 KiB
Go

package json
import (
"encoding/json"
"fmt"
"reflect"
cur "git.loafle.net/overflow/util-go/reflect"
)
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:
b, err := json.Marshal(param)
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)
}
b, err := json.Marshal(param)
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
}