-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverutils.go
96 lines (80 loc) · 2.25 KB
/
serverutils.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
/*
Common utilities for server
*/
package serverutils
import (
"log"
"os"
"strconv"
"strings"
)
var Time timeUtil
var Random randomUtil
var Hash hashUtil
// GetIntegerEnvOrDefault return environment variable value or default value if the variable not exists
func GetEnvOrDefault(key string, defaultValue string) string {
value := os.Getenv(key)
if len(value) == 0 {
value = defaultValue
}
return strings.TrimSpace(value)
}
// GetIntegerEnvOrDefault returns environment variable parsed as int value. If failed to parse environment variables, return default value
func GetIntegerEnvOrDefault(key string, defaultValue int64) (int64, error) {
var retValue int64 = defaultValue
textValue := os.Getenv(key)
if len(textValue) == 0 {
return retValue, nil
}
textValue = strings.TrimSpace(textValue)
parsedValue, errParse := strconv.ParseInt(textValue, 10, 64)
if errParse != nil {
retValue = defaultValue
} else {
retValue = parsedValue
}
return retValue, errParse
}
// GetIntEnvOrDefault returns environment variable parsed as int64 value. If failed to parse environment variables, return default value
func GetInt64EnvOrDefault(key string, defaultValue int64) int64 {
var retValue int64 = defaultValue
textValue := os.Getenv(key)
if len(textValue) == 0 {
return defaultValue
}
textValue = strings.TrimSpace(textValue)
parsedValue, errParse := strconv.ParseInt(textValue, 10, 64)
if errParse != nil {
retValue = defaultValue
} else {
retValue = parsedValue
}
return retValue
}
// GetIntEnvOrDefault returns environment variable parsed as int value. If failed to parse environment variables, return default value
func GetIntEnvOrDefault(key string, defaultValue int) int {
var retValue int = defaultValue
textValue := os.Getenv(key)
if len(textValue) == 0 {
return defaultValue
}
textValue = strings.TrimSpace(textValue)
parsedValue, errParse := strconv.Atoi(textValue)
if errParse != nil {
retValue = defaultValue
} else {
retValue = parsedValue
}
return retValue
}
// GetHostName return host name of running machine
func GetHostName() string {
hostName, _ := os.Hostname()
return hostName
}
// PrintEnv dumps environment to standard output
func PrintEnv() {
for _, env := range os.Environ() {
log.Printf("Environment: %v", env)
}
}