获取配置例子
package main
import (
"flag"
"fmt"
"runtime"
"github.com/spf13/viper"
)
type Config struct {
Base BaseConf `mapstructure:"base"`
}
type BaseConf struct {
pidfile string `mapstructure:"pidfile"`
}
var (
Conf *Config
confPath string
)
func init() {
flag.StringVar(&confPath, "d", "./", " set logic config file path")
}
func InitConfig() (err error) {
Conf = NewConfig()
viper.SetConfigName("logic") // 配置文件的名字
viper.SetConfigType("toml") // 配置文件的类型
viper.AddConfigPath(confPath) // 配置文件的路径
if err := viper.ReadInConfig(); err != nil {
return err
}
if err := viper.Unmarshal(&Conf); err != nil {
panic(fmt.Errorf("unable to decode into struct: %s \n", err))
}
return nil
}
func NewConfig() *Config {
return &Config{
Base: BaseConf{
Pidfile: "/tmp/comet.pid",
},
}
}
# toml 文件内容为
[base]
pidfile = "/tmp/logic.pid"