-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.go
67 lines (61 loc) · 1.13 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
package env
import (
"fmt"
"os"
"strconv"
)
func Str(key string, choices ...string) (value string, err error) {
value, err = get(key)
if err != nil {
return
}
if len(choices) > 0 {
if !in(value, choices) {
err = fmt.Errorf("%s is invalid, choices = %v", key, choices)
}
}
return
}
func Int(key string, choices ...int) (value int, err error) {
s, err := get(key)
if err != nil {
return
}
value, err = strconv.Atoi(s)
if err != nil {
err = fmt.Errorf("%s is not a valid number", key)
return
}
if len(choices) > 0 {
if !in(value, choices) {
err = fmt.Errorf("%s is invalid, choices = %v", key, choices)
}
}
return
}
func Bool(key string) (value bool, err error) {
s, err := get(key)
if err != nil {
return
}
value, err = strconv.ParseBool(s)
if err != nil {
err = fmt.Errorf("%s is not a valid boolean value", key)
}
return
}
func get(key string) (s string, err error) {
s = os.Getenv(key)
if s == "" {
err = fmt.Errorf("%s is not specified", key)
}
return
}
func in[T comparable](value T, array []T) bool {
for _, item := range array {
if value == item {
return true
}
}
return false
}