Files
dypid/config/config.go

48 lines
1.0 KiB
Go

package config
import (
"fmt"
"github.com/spf13/viper"
)
type Config struct {
Host string `mapstructure:"host"`
RunMode string `mapstructure:"run-mode"`
Redis Redis `mapstructure:"redis"`
}
type Redis struct {
Host string `mapstructure:"host"`
Password string `mapstructure:"password"`
DB int `mapstructure:"db"`
}
var APPConfig Config
func InitConfig() {
//设置默认值
defaultConf := Config{
Host: "0.0.0.0:8080",
RunMode: "release",
Redis: Redis{
Host: "localhost:6379",
Password: "",
DB: 0,
},
}
viper.SetDefault("redis", defaultConf)
//设置配置文件名和路径 ./config.toml
viper.AddConfigPath(".")
viper.SetConfigName("config")
viper.SetConfigType("toml")
viper.SafeWriteConfig() //安全写入默认配置
//读取配置文件
if err := viper.ReadInConfig(); err != nil {
fmt.Errorf("无法读取配置文件: %w", err)
}
//解析配置文件
if err := viper.Unmarshal(&APPConfig); err != nil {
fmt.Errorf("无法解析配置: %w", err)
}
}