-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
90 lines (82 loc) · 2.61 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
package util
import (
"os"
"reflect"
jsoniter "github.com/json-iterator/go"
logger "github.com/sirupsen/logrus"
)
// loadDefaultConfig load default config
func loadDefaultConfig[T interface{}](dir string, defaultConfig *T) (*T, ErrorCode) {
var fileName = dir + "/config_default.json"
b, err := os.ReadFile(fileName)
if err != nil {
return nil, Code_Open_File_Failed
}
// var defaultConfig = &SysConfig{}
err = jsoniter.Unmarshal(b, defaultConfig)
if err != nil {
logger.Fatalf("[config][]sys config json to struct error:%v", err)
}
return defaultConfig, 0
}
// InitConfig initialize config
func InitConfig[T interface{}](dir string, env string, processName string, defaultConfig *T, didLoadConfig func(interface{}, string, string)) (*T, ErrorCode) {
var parentDir = dir
if dir[len(dir)-1] == '/' {
parentDir = dir[:len(dir)-1]
}
defaultConfig, errCode := loadDefaultConfig(parentDir, defaultConfig)
if defaultConfig == nil {
return nil, Code_Open_File_Failed
}
sysConfig := defaultConfig
sysConfigRefPtr := reflect.ValueOf(sysConfig)
sysConfigRef := sysConfigRefPtr.Elem()
LoggerValue := sysConfigRef.FieldByName("Logger")
if env == "" {
if LoggerValue != (reflect.Value{}) {
Logger := LoggerValue.Interface().(LoggerConfig)
InitLog(Logger, processName)
}
if didLoadConfig != nil {
didLoadConfig(sysConfig, env, processName)
}
logger.Infof("[config][]run environment:default local ip:%s", localIp)
return sysConfig, Code_Ok
} else {
logger.Infof("[config][]run environment:%s local ip:%s", env, localIp)
}
var fileName = parentDir + "/config_" + env + ".json"
_, fError := os.Stat(fileName)
envConfig := new(T)
if fError == nil || os.IsExist(fError) {
b, err := os.ReadFile(fileName)
if err != nil {
logger.Fatalf("[config][]InitConfig sys config read json error:%v", err)
}
err = jsoniter.Unmarshal(b, envConfig)
if err != nil && errCode != Code_Ok {
if err != nil {
logger.Fatalf("[config][]InitConfig sys config json to struct error:%v", err)
return nil, Code_Load_Config_Failed
} else {
return nil, errCode
}
}
// sysConfig = mergeConfig(envConfig, defaultConfig)
sysConfig = MergeInterface(envConfig, defaultConfig)
} else {
logger.Warnf("[config][]InitConfig env %s no config file", env)
}
sysConfigRefPtr = reflect.ValueOf(sysConfig)
sysConfigRef = sysConfigRefPtr.Elem()
LoggerValue = sysConfigRef.FieldByName("Logger")
if LoggerValue != (reflect.Value{}) {
Logger := LoggerValue.Interface().(LoggerConfig)
InitLog(Logger, processName)
}
if didLoadConfig != nil {
didLoadConfig(sysConfig, env, processName)
}
return sysConfig, Code_Ok
}