-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathutil.go
96 lines (83 loc) · 2.41 KB
/
util.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
package configuration
import (
"fmt"
"os"
"strings"
"time"
)
type optionConverter func(interface{}, interface{}) (interface{}, error)
func convertBool(value interface{}, defval interface{}) (b interface{}, err error) {
switch t := value.(type) {
case bool:
return t, nil
case string:
switch strings.ToLower(t) {
case "true":
return true, nil
case "false":
return false, nil
}
}
return defval, fmt.Errorf("%#+v is not a boolean", value)
}
func convertString(value interface{}, defval interface{}) (b interface{}, err error) {
s, ok := value.(string)
if !ok {
return defval, fmt.Errorf("expected string, not %T", value)
}
return s, err
}
func convertDuration(value interface{}, defval interface{}) (d interface{}, err error) {
s, ok := value.(string)
if !ok {
return defval, fmt.Errorf("expected string, not %T", value)
}
parsed, err := time.ParseDuration(s)
if err != nil {
return defval, fmt.Errorf("parse duration error: %v", err)
}
return parsed, nil
}
func getOptionValue(
envVar string,
optionName string,
defval interface{},
options map[string]interface{},
conversionFunc optionConverter,
) (value interface{}, err error) {
value = defval
if optValue, ok := options[optionName]; ok {
converted, convErr := conversionFunc(optValue, defval)
if convErr != nil {
err = fmt.Errorf("config option %q: invalid value: %v", optionName, convErr)
} else {
value = converted
}
}
if len(envVar) == 0 {
return
}
envValue := os.Getenv(envVar)
if len(envValue) == 0 {
return
}
converted, convErr := conversionFunc(envValue, defval)
if convErr != nil {
err = fmt.Errorf("invalid value of environment variable %s: %v", envVar, convErr)
} else {
value = converted
}
return
}
func getBoolOption(envVar string, optionName string, defval bool, options map[string]interface{}) (bool, error) {
value, err := getOptionValue(envVar, optionName, defval, options, convertBool)
return value.(bool), err
}
func getStringOption(envVar string, optionName string, defval string, options map[string]interface{}) (string, error) {
value, err := getOptionValue(envVar, optionName, defval, options, convertString)
return value.(string), err
}
func getDurationOption(envVar string, optionName string, defval time.Duration, options map[string]interface{}) (time.Duration, error) {
value, err := getOptionValue(envVar, optionName, defval, options, convertDuration)
return value.(time.Duration), err
}