Skip to content

Commit bfda990

Browse files
committed
优化 优先级: 命令行 > 环境变量 > 默认值 功能
1 parent ab4fa15 commit bfda990

File tree

3 files changed

+21
-16
lines changed

3 files changed

+21
-16
lines changed

server/config.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ system:
7878
db-type: "mysql" # support mysql/postgresql/sqlite/sqlserver
7979
need-init-data: false
8080
error-to-email: false
81+
config-env: "GVA_CONFIG"
8182

8283
# captcha configuration
8384
captcha:

server/config/config.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ type System struct {
2222
Addr int `mapstructure:"addr" json:"addr" yaml:"addr"`
2323
DbType string `mapstructure:"db-type" json:"dbType" yaml:"db-type"`
2424
NeedInitData bool `mapstructure:"need-init-data" json:"needInitData" yaml:"need-init-data"`
25-
ErrorToEmail bool `mapstructure:"error-to-email" json:"errorToEmail" yaml:"error-to-email"`
25+
ErrorToEmail bool `mapstructure:"error-to-email" json:"errorToEmail" yaml:"error-to-email"`
26+
ConfigEnv string `mapstructure:"config-env" json:"configEnv" yaml:"config-env"`
2627
}
2728

2829
type JWT struct {

server/core/config.go

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,35 @@
11
package core
22

33
import (
4+
"flag"
45
"fmt"
56
"gin-vue-admin/global"
67
_ "gin-vue-admin/packfile"
78
"github.com/fsnotify/fsnotify"
89
"github.com/spf13/viper"
9-
"github.com/spf13/pflag"
10+
"os"
1011
)
1112

13+
var config string
14+
1215
const defaultConfigFile = "config.yaml"
1316

1417
func init() {
15-
pflag.StringP("configFile","c", "", "choose config file.")
16-
pflag.Parse()
17-
18-
// 优先级: 命令行 > 环境变量 > 默认值
19-
v := viper.New()
20-
v.BindPFlags(pflag.CommandLine)
21-
v.SetEnvPrefix("gva")
22-
v.BindEnv("configFile") // GVA_CONFIGFILE
23-
24-
configFile := v.GetString("configFile")
25-
if configFile == ""{
26-
configFile = defaultConfigFile
18+
flag.StringVar(&config, "c", "", "choose config file.")
19+
flag.Parse()
20+
if config == "" { // 优先级: 命令行 > 环境变量 > 默认值
21+
if configEnv := os.Getenv(global.GVA_CONFIG.System.ConfigEnv); configEnv == "" {
22+
config = defaultConfigFile
23+
fmt.Printf("您正在使用config的默认值,config的路径为%v\n", defaultConfigFile)
24+
} else {
25+
config = configEnv
26+
fmt.Printf("您正在使用GVA_CONFIG环境变量,config的路径为%v\n", config)
27+
}
28+
} else {
29+
fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", config)
2730
}
28-
29-
v.SetConfigFile(configFile)
31+
v := viper.New()
32+
v.SetConfigFile(config)
3033
err := v.ReadInConfig()
3134
if err != nil {
3235
panic(fmt.Errorf("Fatal error config file: %s \n", err))

0 commit comments

Comments
 (0)