Skip to content

Commit 1b19906

Browse files
committed
优先读取当前目录下的配置文件
1 parent bcfd936 commit 1b19906

File tree

1 file changed

+31
-22
lines changed

1 file changed

+31
-22
lines changed

services/load_server_config.go

Lines changed: 31 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@ import (
55
"errors"
66
"github.com/liuguangw/billing_go/common"
77
"gopkg.in/yaml.v2"
8-
"io/ioutil"
8+
"io"
99
"os"
1010
"path/filepath"
11+
"strings"
1112
)
1213

1314
// defaultServerConfig 默认配置
@@ -36,46 +37,54 @@ func LoadServerConfig() (*common.ServerConfig, error) {
3637
}
3738
//程序目录
3839
appDir := filepath.Dir(mainAppPath)
40+
//可选配置文件路径
41+
pathList := []string{
42+
"./config.yaml",
43+
"./config.json",
44+
filepath.Join(appDir, "config.yaml"),
45+
filepath.Join(appDir, "config.json"),
46+
}
3947
var (
40-
configFile *os.File
41-
filenames = []string{"config.yaml", "config.json"}
42-
filenameIndex = -1
48+
configFile *os.File
49+
configFilePath string
4350
)
44-
for index, filename := range filenames {
45-
configFilePath := filepath.Join(appDir, filename)
46-
configFile, err = os.OpenFile(configFilePath, os.O_RDONLY, 0)
51+
for _, fPath := range pathList {
52+
configFile, err = os.Open(fPath)
4753
if err != nil {
4854
//文件不存在
4955
if os.IsNotExist(err) {
5056
continue
5157
}
5258
//其它错误
53-
return nil, errors.New("open config file " + configFilePath + " error: " + err.Error())
59+
return nil, errors.New("open config file " + fPath + " error: " + err.Error())
60+
} else {
61+
//打开成功
62+
configFilePath = fPath
63+
break
5464
}
55-
//打开成功,标记index
56-
filenameIndex = index
57-
break
5865
}
59-
if filenameIndex < 0 {
66+
if configFile == nil {
6067
return nil, errors.New("config file not found")
6168
}
6269
defer configFile.Close()
6370
// 读取配置文件
64-
fileData, err := ioutil.ReadAll(configFile)
71+
fileData, err := io.ReadAll(configFile)
6572
if err != nil {
66-
return nil, errors.New("read config file failed: " + err.Error())
73+
return nil, errors.New("read config file " + configFilePath + " failed: " + err.Error())
6774
}
6875
//初始化配置
6976
serverConfig := defaultServerConfig()
70-
if filenameIndex == 0 {
71-
if err := loadServerConfigFromYaml(fileData, serverConfig); err != nil {
72-
return nil, err
73-
}
74-
return serverConfig, nil
77+
//解析错误
78+
var parseError error
79+
if strings.HasSuffix(configFilePath, ".yaml") {
80+
parseError = loadServerConfigFromYaml(fileData, serverConfig)
81+
} else if strings.HasSuffix(configFilePath, ".json") {
82+
parseError = loadServerConfigFromJSON(fileData, serverConfig)
83+
} else {
84+
return nil, errors.New("config file suffix error")
7585
}
76-
//json格式
77-
if err := loadServerConfigFromJSON(fileData, serverConfig); err != nil {
78-
return nil, err
86+
if parseError != nil {
87+
return nil, errors.New("parse config file " + configFilePath + " failed: " + parseError.Error())
7988
}
8089
return serverConfig, nil
8190
}

0 commit comments

Comments
 (0)