优化读取数据库配置

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