/
config.go
212 lines (197 loc) · 6.11 KB
/
config.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package components
import (
"fmt"
"os"
"reflect"
"sort"
"strconv"
"strings"
"github.com/fananchong/go-xserver/common"
"github.com/fananchong/go-xserver/common/config"
"github.com/fsnotify/fsnotify"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
const frameworkCfgName = "framework.toml"
// Config : 配置组件
type Config struct {
ctx *common.Context
configPath string
app string
suffix string
rootCmd *cobra.Command
viperObjs map[string]*viper.Viper
configObj *config.FrameworkConfig
}
// NewConfig : 实例化
func NewConfig(ctx *common.Context) *Config {
cfg := &Config{
ctx: ctx,
viperObjs: make(map[string]*viper.Viper),
configObj: &config.FrameworkConfig{},
}
cfg.viperObjs[frameworkCfgName] = viper.New()
if err := cfg.init(); err != nil {
fmt.Println(err)
os.Exit(1)
}
ctx.IConfig = cfg
return cfg
}
// Start : 实例化组件
func (*Config) Start() bool {
return true
}
// Close : 关闭组件
func (*Config) Close() {
// No need to do anything
}
const constEnvPrefix string = "GOXSERVER"
func (cfg *Config) init() error {
viperObj := cfg.viperObjs[frameworkCfgName]
cfg.rootCmd = &cobra.Command{
Use: "go-xserver",
Run: func(c *cobra.Command, args []string) {
if appName := viperObj.GetString("app"); appName == "" {
cfg.PrintUsage()
os.Exit(1)
}
},
}
cfg.rootCmd.SetHelpFunc(func(c *cobra.Command, args []string) {
cfg.PrintUsage()
os.Exit(1)
})
flags := cfg.rootCmd.PersistentFlags()
flags.StringVarP(&cfg.configPath, "config", "c", "../config", "配置目录路径")
flags.StringVarP(&cfg.app, "app", "a", "", "应用名(插件,必填)")
flags.StringVarP(&cfg.suffix, "suffix", "s", "", "Log 文件名后缀,多开时可以通过它,避免多个进程共用 1 个 Log 文件")
viperObj.BindPFlags(cfg.rootCmd.PersistentFlags())
cfg.bindConfig(cfg.rootCmd, *cfg.configObj)
cobra.OnInitialize(func() {
viperObj.SetConfigFile(cfg.configPath + "/" + frameworkCfgName)
viperObj.AutomaticEnv()
if err := viperObj.ReadInConfig(); err != nil {
fmt.Println("Failed to read configuration file, err =", err)
os.Exit(1)
}
if err := viperObj.Unmarshal(cfg.configObj); err != nil {
fmt.Println("Parsing the configuration file failed, err =", err)
os.Exit(1)
}
viperObj.WatchConfig()
viperObj.OnConfigChange(func(e fsnotify.Event) {
c := &config.FrameworkConfig{}
if err := viperObj.Unmarshal(c); err != nil {
cfg.ctx.Errorln("Parsing the configuration file failed, err =", err)
} else {
if c.Common.Version != "" {
cfg.configObj = c
cfg.ctx.Printf("Configuration information is: %#v\n", cfg.configObj)
}
}
})
})
return cfg.rootCmd.Execute()
}
func (cfg *Config) bindConfig(c *cobra.Command, s interface{}) {
flags := c.Flags()
cfg.parseStruct(flags, reflect.TypeOf(s), "")
}
func (cfg *Config) parseStruct(flags *pflag.FlagSet, rt reflect.Type, prefix string) {
for i := 0; i < rt.NumField(); i++ {
sf := rt.Field(i)
rawName := strings.ToLower(sf.Name)
if prefix != "" {
rawName = prefix + "." + rawName
}
name := strings.Replace(rawName, ".", "-", -1)
desc := sf.Tag.Get("desc")
defaultValue := sf.Tag.Get("default")
switch sf.Type.Kind() {
case reflect.Struct:
cfg.parseStruct(flags, sf.Type, rawName)
continue
case reflect.Bool:
v, _ := strconv.ParseBool(defaultValue)
flags.Bool(name, v, desc)
case reflect.String:
flags.String(name, defaultValue, desc)
case reflect.Int, reflect.Int32:
v, _ := strconv.ParseInt(defaultValue, 10, 32)
flags.Int(name, int(v), desc)
case reflect.Uint, reflect.Uint32:
v, _ := strconv.ParseUint(defaultValue, 10, 32)
flags.Uint(name, uint(v), desc)
case reflect.Int64:
v, _ := strconv.ParseInt(defaultValue, 10, 64)
flags.Int64(name, int64(v), desc)
case reflect.Uint64:
v, _ := strconv.ParseUint(defaultValue, 10, 64)
flags.Uint64(name, uint64(v), desc)
case reflect.Slice:
var v []string
if defaultValue != "" {
for _, tmp := range strings.Split(strings.Trim(defaultValue, "[]"), ",") {
v = append(v, strings.Trim(tmp, " "))
}
}
flags.StringSlice(name, v, desc)
default:
fmt.Println("bindConfig fail, err = unsupported field: ", rawName)
os.Exit(1)
}
viperObj := cfg.viperObjs[frameworkCfgName]
viperObj.BindPFlag(rawName, flags.Lookup(name))
viperObj.BindEnv(rawName, strings.Replace(fmt.Sprintf("%s_%s", constEnvPrefix, strings.ToUpper(name)), "-", "_", -1))
}
}
// LoadConfig : 逻辑层可以用该接口加载配置文件
func (cfg *Config) LoadConfig(cfgfile string, cfgobj interface{}) bool {
if _, ok := cfg.viperObjs[cfgfile]; ok {
return true
}
cfg.viperObjs[cfgfile] = viper.New()
viperObj := cfg.viperObjs[cfgfile]
viperObj.SetConfigFile(cfg.configPath + "/" + cfgfile)
viperObj.AutomaticEnv()
if err := viperObj.ReadInConfig(); err != nil {
cfg.ctx.Errorf("Failed to read configuration file, err: %s, cfg: %s, path: %s", err.Error(), cfgfile, cfg.configPath)
return false
}
if err := viperObj.Unmarshal(cfgobj); err != nil {
cfg.ctx.Errorf("Parsing the configuration file failed, err: %s, cfg: %s, path: %s", err.Error(), cfgfile, cfg.configPath)
return false
}
viperObj.WatchConfig()
viperObj.OnConfigChange(func(e fsnotify.Event) {
if err := viperObj.Unmarshal(cfgobj); err != nil {
cfg.ctx.Errorf("Parsing the configuration file failed, err: %s, cfg: %s, path: %s", err.Error(), cfgfile, cfg.configPath)
} else {
cfg.ctx.Printf("Configuration information is: %#v\n", cfgobj)
}
})
return true
}
// Config : 获取框架层配置
func (cfg *Config) Config() *config.FrameworkConfig {
return cfg.configObj
}
// PrintUsage : 打印命令行参数
func (cfg *Config) PrintUsage() {
cfg.rootCmd.Usage()
fmt.Println("")
fmt.Println("Environment variables:")
viperObj := cfg.viperObjs[frameworkCfgName]
keys := viperObj.AllKeys()
sort.Sort(sort.StringSlice(keys))
for _, k := range keys {
env := strings.ToUpper(strings.Replace(constEnvPrefix+"_"+k, ".", "_", -1))
fmt.Printf(" %s\n", env)
}
}
// GetViperObj : 获取 viper 对象
func (cfg *Config) GetViperObj() *viper.Viper {
return cfg.viperObjs[frameworkCfgName]
}