@@ -5,9 +5,10 @@ import (
5
5
"errors"
6
6
"github.com/liuguangw/billing_go/common"
7
7
"gopkg.in/yaml.v2"
8
- "io/ioutil "
8
+ "io"
9
9
"os"
10
10
"path/filepath"
11
+ "strings"
11
12
)
12
13
13
14
// defaultServerConfig 默认配置
@@ -36,46 +37,54 @@ func LoadServerConfig() (*common.ServerConfig, error) {
36
37
}
37
38
//程序目录
38
39
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
+ }
39
47
var (
40
- configFile * os.File
41
- filenames = []string {"config.yaml" , "config.json" }
42
- filenameIndex = - 1
48
+ configFile * os.File
49
+ configFilePath string
43
50
)
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 )
47
53
if err != nil {
48
54
//文件不存在
49
55
if os .IsNotExist (err ) {
50
56
continue
51
57
}
52
58
//其它错误
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
54
64
}
55
- //打开成功,标记index
56
- filenameIndex = index
57
- break
58
65
}
59
- if filenameIndex < 0 {
66
+ if configFile == nil {
60
67
return nil , errors .New ("config file not found" )
61
68
}
62
69
defer configFile .Close ()
63
70
// 读取配置文件
64
- fileData , err := ioutil .ReadAll (configFile )
71
+ fileData , err := io .ReadAll (configFile )
65
72
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 ())
67
74
}
68
75
//初始化配置
69
76
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" )
75
85
}
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 ())
79
88
}
80
89
return serverConfig , nil
81
90
}
0 commit comments