forked from xxxsen/qbapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconv.go
51 lines (45 loc) · 1.08 KB
/
conv.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
package qbapi
import (
"fmt"
"reflect"
"strings"
)
func ToMap(in interface{}, tagName string) (map[string]string, error) {
out := make(map[string]string)
IterStruct(in, tagName, func(k string, value interface{}) error {
out[k] = fmt.Sprintf("%v", value)
return nil
})
return out, nil
}
func IterStruct(in interface{}, tagName string, cb func(k string, value interface{}) error) error {
v := reflect.ValueOf(in)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return fmt.Errorf("ToMap only accepts struct or struct pointer; got %T", v)
}
t := v.Type()
for i := 0; i < v.NumField(); i++ {
vf := reflect.ValueOf(v.Field(i).Interface())
//skip nil pointer
if vf.Kind() == reflect.Ptr && vf.IsNil() {
continue
}
if vf.Kind() == reflect.Ptr {
vf = vf.Elem()
}
fi := t.Field(i)
tagValue := fi.Tag.Get(tagName)
if len(tagValue) == 0 {
return fmt.Errorf("contains non tag field:%s", fi.Name)
}
itemList := strings.Split(tagValue, ",")
key := itemList[0]
if err := cb(key, vf); err != nil {
return err
}
}
return nil
}