-
Notifications
You must be signed in to change notification settings - Fork 73
/
utils.go
87 lines (70 loc) · 1.68 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package utils
import (
"context"
"fmt"
"os"
"reflect"
"strings"
"github.com/mitchellh/go-homedir"
log "github.com/sirupsen/logrus"
)
var (
SignalCtx context.Context = getSignalContext()
)
func getSignalContext() context.Context {
ch := make(chan os.Signal, 1)
ctx, cancel := context.WithCancel(context.Background())
go func() {
sig := <-ch
log.Warnf("signal received: %s", sig)
cancel()
}()
return ctx
}
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)
}
}
// GetDefaultConfigDirectory returns the full path to the .newrelic
// directory within the user's home directory.
func GetDefaultConfigDirectory() (string, error) {
home, err := homedir.Dir()
if err != nil {
return "", err
}
return fmt.Sprintf("%s/.newrelic", home), nil
}