slice to struct
func SliceToStruct(array interface{}) (forwardPort *ForwardPort, err error) {
forwardPort = &ForwardPort{}
valueOf := reflect.ValueOf(forwardPort)
if valueOf.Kind() != reflect.Ptr {
return nil, errors.New("must ptr")
}
valueOf = valueOf.Elem()
if valueOf.Kind() != reflect.Struct {
return nil, errors.New("must struct")
}
switch array.(type) {
case []string:
arrayImplement := array.([]string)
for i := 0; i < valueOf.NumField(); i++ {
if i >= len(arrayImplement) {
break
}
val := arrayImplement[i]
if val != "" && reflect.ValueOf(val).Kind() == valueOf.Field(i).Kind() {
valueOf.Field(i).Set(reflect.ValueOf(val))
}
}
case []interface{}:
arrayImplement := array.([]interface{})
for i := 0; i < valueOf.NumField(); i++ {
if i >= len(arrayImplement) {
break
}
val := arrayImplement[i]
if val != "" && reflect.ValueOf(val).Kind() == valueOf.Field(i).Kind() {
valueOf.Field(i).Set(reflect.ValueOf(val))
}
}
}
return forwardPort, nil
}
struct to anything
https://github.com/fatih/structs