-
Notifications
You must be signed in to change notification settings - Fork 1
/
helper.go
81 lines (68 loc) · 1.61 KB
/
helper.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
package goopentelemetry
import (
"context"
"fmt"
"github.com/agiledragon/gomonkey/v2"
"github.com/spf13/cast"
"go.opentelemetry.io/otel/trace"
"os"
"runtime"
"strings"
)
// TracerPatch for unit test monkey patch
func TracerPatch() (ctx context.Context, reset func()) {
ctx = context.Background()
tracerPatch := gomonkey.ApplyFunc(NewSpan, func(ctx context.Context, name, operation string) (context.Context, trace.Span) {
return ctx, trace.SpanFromContext(ctx)
})
return ctx, func() {
tracerPatch.Reset()
}
}
func GetEnvOrDefault(key string, defaultValue interface{}) interface{} {
value := os.Getenv(key)
if len(value) == 0 {
return defaultValue
}
return value
}
func GetEnv(key string) string {
value := GetEnvOrDefault(key, "").(string)
return value
}
func StringToBool(value string) bool {
if value == "true" {
return true
}
return false
}
func GetActionName() string {
c, _, _, _ := runtime.Caller(1)
f := runtime.FuncForPC(c).Name()
fs := strings.SplitN(f, ".", 2)
replacer := strings.NewReplacer("(", "", ")", "", "*", "")
actionName := replacer.Replace(fs[1])
return actionName
}
func WriteStringTemplate(stringTemplate string, args ...interface{}) string {
return fmt.Sprintf(stringTemplate, args...)
}
func AnyToBool(value any) bool {
return cast.ToBool(value)
}
func GetFunctionName(skip int) string {
pc, _, _, ok := runtime.Caller(skip)
if !ok {
return ""
}
details := runtime.FuncForPC(pc)
if details == nil {
return ""
}
funcName := details.Name()
lastDot := strings.LastIndex(funcName, ".")
if lastDot != -1 {
funcName = funcName[lastDot+1:]
}
return funcName
}