-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructandmap.go
70 lines (59 loc) · 1.5 KB
/
structandmap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package utils
import (
"errors"
"reflect"
)
/*func Struct2Map(obj interface{}) map[string]interface{} {
t := reflect.TypeOf(obj)
v := reflect.ValueOf(obj)
var data = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
data[t.Field(i).Name] = v.Field(i).Interface()
}
return data
}
*/
func Struct2Map(obj interface{}) map[string]interface{} {
v := reflect.ValueOf(obj)
if v.Kind() == reflect.Ptr {
v = v.Elem()
obj = v.Interface()
v = reflect.ValueOf(obj)
}
t := reflect.TypeOf(obj)
var data = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
data[t.Field(i).Name] = v.Field(i).Interface()
}
return data
}
func setField(obj interface{}, name string, value interface{}) error {
structValue := reflect.ValueOf(obj).Elem()
structFieldValue := structValue.FieldByName(name)
if !structFieldValue.IsValid() {
return errors.New("No such field: %s in obj" + name)
}
if !structFieldValue.CanSet() {
return errors.New("Cannot set %s field value" + name)
}
structFieldType := structFieldValue.Type()
val := reflect.ValueOf(value)
if structFieldType != val.Type() {
return errors.New("Provided value type didn't match obj field type")
}
structFieldValue.Set(val)
return nil
}
type RPCConfig struct {
ip string
port string
}
func (s *RPCConfig) FillStruct(m map[string]string) error {
for k, v := range m {
err := setField(s, k, v)
if err != nil {
return err
}
}
return nil
}