带有毒蛇的嵌套结构片段

时间:2019-02-01 08:40:34

标签: go environment-variables 12factor viper-go

有没有一种方法可以通过环境变量传递嵌套的任意结构的切片?下面的代码可以与yaml配置文件一起正常工作,但是我无法通过env(用于生产环境)使它正常工作

package main

import (
    "log"
    "strings"

    "github.com/spf13/viper"
)

type HostConfig struct {
    Host string `mapstructure:"host"`
    Port int    `mapstructure:"port"`
}

type Config struct {
    ClusterMode bool `mapstructure:"cluster_mode"`

    Hosts []HostConfig `mapstructure:"hosts"`
}

func main() {
    viper.SetEnvPrefix("service")

    replacer := strings.NewReplacer(".", "_")
    viper.SetEnvKeyReplacer(replacer)

    viper.AutomaticEnv()

    var cfg Config
    err := viper.UnmarshalKey("redis", &cfg)

    log.Printf("cfg: %+v\n\nerr: %+v", cfg, err)
}
$ SERVICE_REDIS={"cluster_mode":"true","hosts":[{"host":"abc","port":123}]} go run main.go
2019/02/01 12:50:53 cfg: {ClusterMode:false PoolSize:0 Hosts:[]}

err: '' expected a map, got 'string'

0 个答案:

没有答案