游戏节点配置嵌入在一个配置文件中
This commit is contained in:
24
cmd/root.go
24
cmd/root.go
@@ -4,8 +4,11 @@ Copyright © 2024 慕枫Go <mapleafgo@163.com>
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"game-driver/config"
|
||||
"game-driver/config/game"
|
||||
"game-driver/internal"
|
||||
"io/fs"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
@@ -45,22 +48,35 @@ func Execute() {
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
|
||||
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "config.yml", "默认当前目录下的config.yml")
|
||||
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "config.yml", "默认当前目录下的 config.yml")
|
||||
}
|
||||
|
||||
// initConfig reads in config file and ENV variables if set.
|
||||
func initConfig() {
|
||||
viper.SetConfigFile(cfgFile)
|
||||
|
||||
viper.AutomaticEnv() // read in environment variables that match
|
||||
|
||||
// If a config file is found, read it in.
|
||||
if err := viper.ReadInConfig(); err == nil {
|
||||
log.Printf("Using config file: %s", viper.ConfigFileUsed())
|
||||
} else if errors.Is(err, fs.ErrNotExist) {
|
||||
log.Printf("无法找到主配置文件: %s", viper.ConfigFileUsed())
|
||||
os.Exit(1)
|
||||
} else {
|
||||
log.Panicln("read config file error: ", err)
|
||||
}
|
||||
|
||||
err := viper.Unmarshal(&config.C)
|
||||
if err != nil {
|
||||
log.Panicln("unmarshal config failed: ", err)
|
||||
}
|
||||
|
||||
// 初始化游戏节点配置
|
||||
game.G = game.NewConfig(config.C.Point)
|
||||
if game.G != nil { // 如果需要游戏配置
|
||||
err = viper.UnmarshalKey("game", &game.G)
|
||||
if err != nil {
|
||||
log.Panicln("unmarshal game config failed: ", err)
|
||||
}
|
||||
} else {
|
||||
log.Panicln("game config not found")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user