-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfig.go
101 lines (91 loc) · 1.86 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
package cfg
import (
"cloudCli/common"
"cloudCli/utils"
"errors"
"gopkg.in/yaml.v3"
"log"
"os"
"reflect"
"strings"
)
/**
* 系统配置
* @author jensen.chen
* @date 2022-05-21
*/
type Config struct {
Data map[string]interface{}
}
var CliConfig Config = Config{}
/**
* 获取配置
* 配置的KEY可以用.分割,比如inspect.cron\
* 如果找不到配置,则返回指定的默认值
*/
func GetConfigValue(key string, defaultValue interface{}) (interface{}, error) {
val, err := GetConfig(key)
if err != nil {
return defaultValue, nil
}
if val != nil {
return val, nil
} else {
return defaultValue, nil
}
}
/**
* 获取配置
* 配置的KEY可以用.分割,比如inspect.cron
*/
func GetConfig(key string) (interface{}, error) {
keyAry := strings.Split(key, common.KEY_DELIMITER)
var val interface{} = CliConfig.Data
for _, itemKey := range keyAry {
val = getMapValue(val.(map[string]interface{}), itemKey)
if val == nil {
break
}
}
if val != nil {
return val, nil
} else {
return nil, errors.New("Config Not Exists")
}
}
func GetKeys(data map[string]interface{}) []string {
j := 0
keys := make([]string, len(data))
for k := range data {
keys[j] = k
j++
}
return keys
}
func getMapValue(data map[string]interface{}, key string) interface{} {
rs, _ := data[key]
return rs
}
/**
配置项自动写入struct变量
@key 配置项的ROOT键值
@target Struct指针
*/
func ConfigMapping(key string, target interface{}) {
config, _ := GetConfig(key)
if config != nil && reflect.ValueOf(config).Kind() == reflect.Map {
data := config.(map[string]interface{})
utils.MapToStruct(data, target, "config")
}
}
func Load(path string) {
log.Println("Read Config", path)
f, err := os.Open(path)
if err != nil {
return
}
defer f.Close()
decode := yaml.NewDecoder(f)
decode.Decode(&(CliConfig.Data))
log.Println(CliConfig.Data)
}