-
Notifications
You must be signed in to change notification settings - Fork 0
/
conf.go
93 lines (82 loc) · 1.73 KB
/
conf.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
package config
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"strings"
)
/*
*@Author Administrator
*@Date 31/3/2021 11:06
*@desc
*/
var configDefult = Config{
Name: "app",
Path: "conf",
Ext: "yaml",
}
type ConfigFn func(config *Config) *Config
// Name /*
func Name(name string) ConfigFn {
return func(config *Config) *Config {
config.Name = name
return config
}
}
// Path /*
func Path(path string) ConfigFn {
return func(config *Config) *Config {
config.Path = path
return config
}
}
// Ext /*
func Ext(ext string) ConfigFn {
return func(config *Config) *Config {
config.Ext = ext
return config
}
}
func NewConfig(configList ...ConfigFn) error {
if len(configList) > 0 {
for _, fn := range configList {
fn(&configDefult)
}
}
return configDefult.InitConfig()
}
type Config struct {
Name string //文件名称
Path string //文件路径
Ext string //文件后缀
}
func (c *Config) InitConfig() error {
viper.AddConfigPath(c.Path)
viper.SetConfigName(c.Name)
viper.SetConfigType(c.Ext)
// 设置配置文件格式为YAML
viper.AutomaticEnv() // 读取匹配的环境变量
viper.SetEnvPrefix("APISERVER") // 读取环境变量的前缀为APISERVER
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
if err := viper.ReadInConfig(); err != nil { // viper解析配置文件
return err
}
mapString := viper.GetStringMapString("LoadConfig")
for fileName, ext := range mapString {
if ext == "" {
ext = c.Ext
}
viper.SetConfigName(fileName)
viper.SetConfigType(ext)
err := viper.MergeInConfig()
if err != nil {
return err
}
}
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println(e.Name)
})
return nil
}