使用viper读取配置文件
配置文件config.yml
mysql:
  type: mysql
  dsn: "user:pass@tcp(localhost:30306)/db_name?charset=utf8&parseTime=True&loc=Local"
  maxopen: 100
  maxidle: 10
  maxlifetime: 300
redis:
  host: 127.0.0.1
  port: 3306
读取配置文件
package config
import (
    "github.com/spf13/viper"
    "path"
    "runtime"
    "time"
)
type mysqlConfig struct { // 配置属性跟类型字段不同名是要加下面这个tag
    Type        string        `mapstructure:"type"`
    DSN         string        `mapstructure:"dsn"`
    MaxOpenConn int           `mapstructure:"maxopen"`
    MaxIdleConn int           `mapstructure:"maxidle"`
    MaxLifeTime time.Duration `mapstructure:"maxlifetime"`
}
type redisConfig struct { // 配置属性跟类型字段不同名是要加下面这个tag
    Host string `mapstructure:"host"`
    Port string `mapstructure:"port"`
}
var Mysql *mysqlConfig
var Redis *redisConfig
func init() {
    // 获取当前文件的路径
    _, filename, _, _ := runtime.Caller(0)
    // 配置文件目录的路径
    configBaseDir := path.Dir(filename)
    vp := viper.New()
    vp.AddConfigPath(configBaseDir)
    vp.SetConfigType("yaml")
    err := vp.ReadInConfig()
    if err != nil {
	panic(err)
    }
    vp.UnmarshalKey("mysql", &Mysql)
    vp.UnmarshalKey("redis", &Redis)
    Mysql.MaxLifeTime *= time.Second
}
调用配置内容
import (
    "fmt"
    "lianxi/config"
)
func main() {
    fmt.Println(config.Redis.Port)
    fmt.Println(config.Mysql.Type)
}
参考文档 https://zhuanlan.zhihu.com/p/485608958 https://www.cnblogs.com/randysun/p/15889494.html
 
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号