-
Notifications
You must be signed in to change notification settings - Fork 71
/
utils.go
184 lines (150 loc) · 3.59 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package utils
import (
"context"
b64 "encoding/base64"
"fmt"
"net/url"
"os"
"os/signal"
"reflect"
"strconv"
"strings"
"syscall"
"time"
"github.com/mitchellh/go-homedir"
log "github.com/sirupsen/logrus"
)
var (
SignalCtx = 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.Debugf("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()
}
// MakeRange generates a slice of sequential integers.
func MakeRange(min, max int) []int {
a := make([]int, max-min+1)
for i := range a {
a[i] = min + i
}
return a
}
// Base64Encode base 64 encodes a string.
func Base64Encode(data string) string {
return b64.StdEncoding.EncodeToString([]byte(data))
}
// Standard way to check for stdin in most environments (https://stackoverflow.com/questions/22563616/determine-if-stdin-has-data-with-go)
func StdinExists() bool {
fi, err := os.Stdin.Stat()
if err != nil {
return false
}
return (fi.Mode() & os.ModeCharDevice) == 0
}
func StringInSlice(str string, slice []string) bool {
for _, s := range slice {
if str == s {
return true
}
}
return false
}
func IntSliceToStringSlice(in []int) (out []string) {
for _, i := range in {
out = append(out, strconv.Itoa(i))
}
return out
}
// Obfuscate receives a string, and replaces everything after the first 8
// characters with an asterisk before returning the result.
func Obfuscate(input string) string {
result := make([]string, len(input))
parts := strings.Split(input, "")
for i, x := range parts {
if i < 8 {
result[i] = x
} else {
result[i] = "*"
}
}
return strings.Join(result, "")
}
func IsAbsoluteURL(rawURL string) bool {
u, err := url.Parse(rawURL)
if err != nil {
return false
}
return u.Scheme != "" && u.Host != ""
}
func IsExitStatusCode(exitCode int, err error) bool {
exitCodeString := fmt.Sprintf("exit status %d", exitCode)
return strings.Contains(err.Error(), exitCodeString)
}