-
Notifications
You must be signed in to change notification settings - Fork 73
/
utils.go
109 lines (88 loc) · 2.04 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package utils
import (
"context"
"fmt"
"os"
"os/signal"
"reflect"
"strings"
"syscall"
"time"
"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())
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
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
}
// MinOf returns the minimum int value provided.
func MinOf(vars ...int) int {
min := vars[0]
for _, i := range vars {
if min > i {
min = i
}
}
return min
}
// GetTimestamp returns the current epoch timestamp in seconds.
func GetTimestamp() int64 {
return time.Now().Unix()
}