enterprise/common/config/corp.go

78 lines
1.5 KiB
Go
Raw Normal View History

2025-03-14 14:29:55 +08:00
package config
import (
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/smbrave/goutil"
"github.com/spf13/cast"
"os"
"strings"
)
var (
corpConfig map[int64]map[string]interface{}
)
func init() {
corpConfig = make(map[int64]map[string]interface{})
}
// 配置优先级 环境变量>数据库配置>大于文件配置
func LoadCorpConfig() {
fileList, err := goutil.FileList("conf/corp/")
if err != nil {
panic(err)
}
filePath := "conf/corp/default.json"
cfgBody, _ := os.ReadFile(filePath)
defParams := make(map[string]interface{})
if err := json.Unmarshal(cfgBody, &defParams); err != nil {
panic(err)
}
for _, file := range fileList {
if !strings.HasSuffix(file, ".json") {
continue
}
appId := cast.ToInt64(strings.TrimRight(file, ".json"))
filePath = fmt.Sprintf("conf/corp/%s", file)
cfgBody, _ = os.ReadFile(filePath)
p := make(map[string]interface{})
if err := json.Unmarshal(cfgBody, &p); err != nil {
panic(err)
}
allParmas := make(map[string]interface{})
for k, v := range defParams {
allParmas[k] = v
}
for k, v := range p {
allParmas[k] = v
}
log.Infof("corpId[%d] config[%s]", appId, goutil.EncodeJSON(allParmas))
corpConfig[appId] = allParmas
}
}
func GetCorpConfig(corpId int64, key string, def ...interface{}) interface{} {
if _, ok := corpConfig[corpId]; !ok {
if len(def) == 0 {
return nil
}
return def[0]
}
cfg := corpConfig[corpId]
if v, ok := cfg[key]; ok {
return v
}
if len(def) == 0 {
return nil
}
return def[0]
}