优化读取数据库配置

This commit is contained in:
白茶清欢 2022-06-11 18:25:00 +08:00
parent 879c9df7cc
commit 7cca5c5939
1 changed files with 50 additions and 30 deletions

View File

@ -8,6 +8,7 @@
package mysql
import (
"errors"
"fmt"
"path/filepath"
"strings"
@ -67,45 +68,64 @@ func (c *client) BatchAddWithConfigDir(cfgDir string) error {
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:39 2022/6/9
func (c *client) getMysqlCfgFileList(cfgDir string) ([]cfgFile, error) {
func (c *client) getMysqlCfgFileList(cfgDir string) ([]*cfgFile, error) {
filepathNames, _ := filepath.Glob(filepath.Join(cfgDir, "*"))
cfgFileList := make([]cfgFile, 0)
cfgFileList := make([]*cfgFile, 0)
for i := range filepathNames {
fileArr := strings.Split(filepathNames[i], ".")
if len(fileArr) < 2 {
// 获取不到类型
continue
}
fileType := strings.ToLower(fileArr[len(fileArr)-1])
var (
err error
err error
cfgInfo *cfgFile
)
cfgInfo := cfgFile{
Path: filepathNames[i],
Type: FileTypeYaml,
Config: Mysql{},
}
switch fileType {
case FileTypeYaml:
fallthrough
case FileTypeYml:
cfgInfo.Type = FileTypeYaml
if err = util.File.ReadYmlContent(filepathNames[i], &cfgInfo); nil != err {
return nil, fmt.Errorf("%s 配置文件解析失败, 原因 : %s", cfgInfo.Path, err.Error())
}
case FileTypeJson:
cfgInfo.Type = FileTypeJson
if err = util.File.ReadJSONContent(filepathNames[i], &cfgInfo); nil != err {
return nil, fmt.Errorf("%s 配置文件解析失败, 原因 : %s", cfgInfo.Path, err.Error())
}
default:
// 不是JSON , 也不是YML, 跳过
continue
if cfgInfo, err = c.getCfg(filepathNames[i]); nil != err {
return nil, err
}
cfgFileList = append(cfgFileList, cfgInfo)
}
return cfgFileList, nil
}
// getCfg 读取配置
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:05 2022/6/11
func (c *client) getCfg(cfgPath string) (*cfgFile, error) {
result := &cfgFile{
Path: cfgPath,
Type: "",
Config: Mysql{},
}
fileArr := strings.Split(cfgPath, ".")
if len(fileArr) < 2 {
// 获取不到类型
return nil, errors.New("文件格式必须是JSON或者YAML")
}
fileType := strings.ToLower(fileArr[len(fileArr)-1])
var (
err error
cfgInfo Mysql
)
switch fileType {
case FileTypeYaml:
fallthrough
case FileTypeYml:
result.Type = FileTypeYaml
if err = util.File.ReadYmlContent(cfgPath, &result.Config); nil != err {
return nil, fmt.Errorf("%s 配置文件解析失败, 原因 : %s", cfgPath, err.Error())
}
return result, nil
case FileTypeJson:
result.Type = FileTypeJson
if err = util.File.ReadJSONContent(cfgPath, &cfgInfo); nil != err {
return nil, fmt.Errorf("%s 配置文件解析失败, 原因 : %s", cfgPath, err.Error())
}
return result, nil
default:
// 不是JSON , 也不是YML, 跳过
return nil, nil
}
}
// GetDBClient 获取db client
//
// Author : go_developer@163.com<白茶清欢>