-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
79 lines (66 loc) · 1.78 KB
/
convert.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
71
72
73
74
75
76
77
78
79
// Copyright 2013 The StudyGolang Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// http://studygolang.com
// Author: polaris polaris@studygolang.com
package util
import (
"fmt"
"reflect"
"strings"
)
func Struct2Map(dest map[string]interface{}, src interface{}) error {
if dest == nil {
return fmt.Errorf("Struct2Map(dest is %v)", dest)
}
srcType := reflect.TypeOf(src)
srcValue := reflect.Indirect(reflect.ValueOf(src))
if srcValue.Kind() != reflect.Struct {
return fmt.Errorf("Struct2Map(non-struct %s)", srcType)
}
srcType = srcValue.Type()
fieldNum := srcType.NumField()
for i := 0; i < fieldNum; i++ {
// struct 字段的反射类型(StructField)
fieldType := srcType.Field(i)
// 非导出字段不处理
if fieldType.PkgPath != "" {
continue
}
tag := fieldType.Tag.Get("json")
fieldValue := srcValue.Field(i)
// json 有 key,omitempty 的情况
tag = strings.Split(tag, ",")[0]
if tag == "" {
tag = UnderscoreName(fieldType.Name)
}
dest[tag] = fieldValue.Interface()
}
return nil
}
// model中类型提取其中的 idField(int 类型) 属性组成 slice 返回
func Models2Intslice(models interface{}, idField string) []int {
if models == nil {
return []int{}
}
// 类型检查
modelsValue := reflect.ValueOf(models)
if modelsValue.Kind() != reflect.Slice {
return []int{}
}
var modelValue reflect.Value
length := modelsValue.Len()
ids := make([]int, 0, length)
for i := 0; i < length; i++ {
modelValue = reflect.Indirect(modelsValue.Index(i))
if modelValue.Kind() != reflect.Struct {
continue
}
val := modelValue.FieldByName(idField)
if val.Kind() != reflect.Int {
continue
}
ids = append(ids, int(val.Int()))
}
return ids
}