-
Notifications
You must be signed in to change notification settings - Fork 0
/
config2.go
95 lines (74 loc) · 2.01 KB
/
config2.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
package config2
import (
"encoding/json"
"flag"
"io/ioutil"
"log"
"os"
"reflect"
)
const (
usageTag = "usage"
)
// Check config to be a pointer to struct.
func checkConfig(config interface{}) {
configType := reflect.TypeOf(config)
if configType.Kind() != reflect.Ptr {
log.Fatal("Config not a pointer")
}
configValueType := configType.Elem()
if configValueType.Kind() != reflect.Struct {
log.Fatal("Config not a pointer to struct")
}
}
// Parse command line arguments.
func ParseCommandLine(args []string, config interface{}) *flag.FlagSet {
checkConfig(config)
configType := reflect.TypeOf(config).Elem()
configValue := reflect.ValueOf(config).Elem()
flagSet := flag.NewFlagSet(configType.Name(), flag.ExitOnError)
for i := 0; i < configType.NumField(); i++ {
field := configType.Field(i)
value := configValue.Field(i)
usage := field.Tag.Get(usageTag)
fv := &fieldValue{
Kind: field.Type.Kind(),
Value: value,
}
flagSet.Var(fv, field.Name, usage)
}
flagSet.Parse(args)
return flagSet
}
// Parse the environment variables.
func ParseEnvironmentVariables(prefix string, config interface{}) {
checkConfig(config)
configType := reflect.TypeOf(config).Elem()
configValue := reflect.ValueOf(config).Elem()
for i := 0; i < configType.NumField(); i++ {
field := configType.Field(i)
value, ok := os.LookupEnv(prefix + field.Name)
if ok {
fv := &fieldValue{
Kind: field.Type.Kind(),
Value: configValue.Field(i),
}
setFieldValue(fv, value)
}
}
}
// Parse configuration variables from JSON file.
func ParseJson(fileName string, config interface{}) error {
checkConfig(config)
data, err := ioutil.ReadFile(fileName)
if err != nil {
return err
}
return json.Unmarshal(data, config)
}
// Parse the JSON file if exists, parse the environment variables, and parse the command line arguments.
func ParseAll(fileName string, prefix string, config interface{}) {
ParseJson(fileName, config)
ParseEnvironmentVariables(prefix, config)
ParseCommandLine(os.Args, config)
}