-
Notifications
You must be signed in to change notification settings - Fork 73
/
utils.go
56 lines (44 loc) · 1.07 KB
/
utils.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
package utils
import (
"reflect"
"strings"
log "github.com/sirupsen/logrus"
)
type StructToMapCallback func(item interface{}, fields []string) map[string]interface{}
func StructToMap(item interface{}, fields []string) map[string]interface{} {
v := reflect.TypeOf(item)
reflectValue := reflect.ValueOf(item)
reflectValue = reflect.Indirect(reflectValue)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
mapped := map[string]interface{}{}
for _, field := range fields {
for i := 0; i < v.NumField(); i++ {
value := reflectValue.Field(i).Interface()
tag := v.Field(i).Tag
if tag != "" && tag != "-" {
tagKey := tag.Get("json")
jsonKey := strings.Split(tagKey, ",")[0]
if jsonKey == field {
mapped[field] = value
}
}
}
}
return mapped
}
// LogIfError wraps the err nil check to cleanup the code.
// Logs at Error level
func LogIfError(err error) {
if err != nil {
log.Error(err)
}
}
// LogIfFatal wraps the err nil check to cleanup the code.
// Logs at Fatal level
func LogIfFatal(err error) {
if err != nil {
log.Fatal(err)
}
}