-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.go
75 lines (60 loc) · 1.29 KB
/
env.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
package env
import (
"os"
"strconv"
"strings"
"github.com/etkecc/go-env/dotenv"
)
var envprefix string
func init() {
dotenv.Load()
}
// SetPrefix sets prefix for all env vars
func SetPrefix(prefix string) {
envprefix = prefix
}
// String returns string vars
func String(shortkey string, defaultValue ...string) string {
var dv string
if len(defaultValue) > 0 {
dv = defaultValue[0]
}
key := strings.ToUpper(envprefix + "_" + strings.ReplaceAll(shortkey, ".", "_"))
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return dv
}
return value
}
// Int returns int vars
func Int(shortkey string, defaultValue ...int) int {
var dv int
if len(defaultValue) > 0 {
dv = defaultValue[0]
}
str := String(shortkey)
if str == "" {
return dv
}
val, err := strconv.Atoi(str)
if err != nil {
return dv
}
return val
}
// Bool returns boolean vars (1, true, yes)
func Bool(shortkey string) bool {
str := strings.ToLower(String(shortkey))
if str == "" {
return false
}
return (str == "1" || str == "true" || str == "yes")
}
// Slice returns slice from space-separated strings, eg: export VAR="one two three" => []string{"one", "two", "three"}
func Slice(shortkey string) []string {
str := String(shortkey)
if str == "" {
return nil
}
return strings.Split(str, " ")
}