/
common.go
125 lines (98 loc) · 2.11 KB
/
common.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
package common
import (
"flag"
"fmt"
"runtime"
"sync"
"math/rand"
"os/user"
"strings"
"time"
)
var (
onceShutdownHooks sync.Once
shutdownHooks []func() error
UserName *string
UserHomeDir *string
)
func init() {
shutdownHooks = make([]func() error, 0)
UserName = new(string)
UserHomeDir = new(string)
usr, err := user.Current()
if err == nil {
*UserHomeDir = usr.HomeDir
}
UserName = flag.String("user.name", *UserName, "user name")
UserHomeDir = flag.String("user.homedir", *UserHomeDir, "user home directory")
}
// Exit exist app and run all registered shutdown hooks
func Cleanup() {
runShutdownHooks()
}
func runShutdownHooks() {
onceShutdownHooks.Do(func() {
for _, f := range shutdownHooks {
err := f()
if err != nil {
Error(err)
}
}
})
}
func AddShutdownHook(f func() error) {
shutdownHooks = append(shutdownHooks, nil)
copy(shutdownHooks[1:], shutdownHooks[0:])
shutdownHooks[0] = f
}
// IsWindowsOS reports true if underlying OS is MS Windows
func IsWindowsOS() bool {
result := runtime.GOOS == "windows"
return result
}
// IsLinuxOS reports true if underlying OS is Linux
func IsLinuxOS() bool {
result := runtime.GOOS == "linux"
return result
}
// IsMacOS reports true if underlying OS is MacOS
func IsMacOS() bool {
result := runtime.GOOS == "darwin"
return result
}
// IsAMD64 reports true if underlying OS is 64Bit ready
func IsAMD64() bool {
result := runtime.GOARCH == "amd64"
Debug(fmt.Sprintf("isAMD64 : %v", result))
return result
}
func ToBool(s string) bool {
if len(s) == 0 {
return false
}
s = strings.ToLower(s)
return s == "true" || s == "t"
}
// Translate a i18n message
func Translate(msg string, args ...interface{}) string {
return fmt.Sprintf(msg, args...)
}
func Eval(b bool, trueFunc interface{}, falseFunc interface{}) interface{} {
if b {
if f, ok := trueFunc.(func() interface{}); ok {
return f()
} else {
return trueFunc
}
} else {
if f, ok := falseFunc.(func() interface{}); ok {
return f()
} else {
return falseFunc
}
}
}
func Rnd(max int) int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(max)
}