dev-config.yaml
serverName: "golang入门"
redisConfig:
redisHost: "127.0.0.1"
redisPort: 6379
pro-config.yaml
serverName: "golang精通"
redisConfig:
redisHost: "192.168.11.11"
redisPort: 6380
main.go
package main
import (
"fmt"
"github.com/spf13/viper"
)
type RedisConfig struct {
RedisHost string `mapstructure:"redisHost"`
RedisPort int32 `mapstructure:"redisPort"`
}
type ServerConfig struct {
ServerName string `mapstructure:"serverName"`
RedisConfig `mapstructure:"redisConfig"`
}
func GetEnv(s string) int {
viper.AutomaticEnv()
return viper.GetInt(s)
}
func main() {
v := viper.New()
dev := GetEnv("DEV")
fmt.Println("env DEV:", dev)
configFilePath := "dev-config.yaml"
if dev == 0 {
configFilePath = "pro-config.yaml"
}
v.SetConfigFile(configFilePath)
err := v.ReadInConfig()
if err != nil {
panic(err)
}
var serverConfig ServerConfig
err = v.Unmarshal(&serverConfig)
if err != nil {
panic(err)
}
fmt.Println(serverConfig.ServerName)
fmt.Println(serverConfig.RedisConfig.RedisHost)
fmt.Println(serverConfig.RedisConfig.RedisPort)
}
windows 11 的 PowerShell 环境变量
设置
$ENV:DEV=1
查看
$ENV
删除
$ENV:DEV=''
linux 环境变量
export DEV=1