下面是我的 toml 格式的配置文件。
[[hosts]]
name = "host1"
username = "user1"
password = "password1"
[[hosts]]
name = "host2"
username = "user2"
password = "password2"
...这是我加载它的代码:
import (
"fmt"
"github.com/spf13/viper"
"strings"
)
type Config struct {
Hosts []Host
}
type Host struct {
Name string `mapstructure:"name"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
}
func main() {
viper.AddConfigPath(".")
viper.AddConfigPath("./config")
viper.SetConfigName("app")
if err := viper.ReadInConfig(); err != nil {
return nil, fmt.Errorf("error reading config file, %v", err)
}
config := new(Config)
if err := viper.Unmarshal(config); err != nil {
return nil, fmt.Errorf("error parsing config file, %v", err)
}
var username, password string
for i, h := range config.Hosts {
if len(h.Name) == 0 {
return nil, fmt.Errorf("name not defined for host %d", i)
}
if username = os.Getenv(strings.ToUpper(h.Name) + "_" + "USERNAME"); len(username) > 0 {
config.Hosts[i].Username = username
} else if len(h.Username) == 0 {
return nil, fmt.Errorf("username not defined for %s", e.Name)
}
if password = os.Getenv(strings.ToUpper(e.Name) + "_" + "PASSWORD"); len(password) > 0 {
config.Hosts[i].Password = password
} else if len(h.Password) == 0 {
return nil, fmt.Errorf("password not defined for %s", e.Name)
}
fmt.Printf("Hostname: %s", h.name)
fmt.Printf("Username: %s", h.Username)
fmt.Printf("Password: %s", h.Password)
}
}
例如,我首先检查环境变量HOST1_USERNAME1
, HOST1_PASSWORD1
,HOST2_USERNAME2
和是否HOST2_PASSWORD2
存在...如果存在,则将配置项设置为它们的值,否则我尝试从配置文件中获取值。
我知道 viper 提供AutomaticEnv
了做类似事情的方法......但它是否适用于像我这样的集合(AutomaticEnv
应在环境变量绑定后调用)?
鉴于我上面的代码,是否可以使用 viper 和 remove 提供的机制os.GetEnv
?
谢谢。
更新
下面是我更新的代码。在我定义了环境变量HOST1_USERNAME
并将HOST1_PASSWORD
配置文件中的相应设置设置为空字符串。
这是我的新配置文件:
[host1]
username = ""
password = ""
[host2]
username = "user2"
password = "password2"
这是我的代码:
package config
import (
"fmt"
"github.com/spf13/viper"
"strings"
"sync"
)
type Config struct {
Hosts []Host
}
type Host struct {
Name string
Username string
Password string
}
var config *Config
func (c *Config) Load() (*Config, error) {
if config == nil {
viper.AddConfigPath(".")
viper.AddConfigPath("./config")
viper.SetConfigName("myapp")
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
if err := viper.ReadInConfig(); err != nil {
return nil, fmt.Errorf("error reading config file, %v", err)
}
allSettings := viper.AllSettings()
hosts := make([]Host, 0, len(allSettings))
for key, value := range allSettings {
val := value.(map[string]interface{})
if val["username"] == nil {
return nil, fmt.Errorf("username not defined for host %s", key)
}
if val["password"] == nil {
return nil, fmt.Errorf("password not defined for host %s", key)
}
hosts = append(hosts, Host{
Name: key,
Unsername: val["username"].(string),
Password: val["password"].(string),
})
}
config = &Config{hosts}
}
return config, nil
}
我现在工作(感谢 Chrono Kitsune),希望对您有所帮助,j3d