如何使用viper将环境变量解组为切片?

时间:2017-04-03 04:14:31

标签: go viper-go

我有以下代码:

package main

import (
    "log"

    "github.com/spf13/viper"
)

func main() {
    viper.SetEnvPrefix("myprefix")
    viper.SetDefault("languages", []string{"french", "spanish"})
    viper.BindEnv("name")
    viper.BindEnv("languages")

    type config struct {
        Name      string
        Languages []string
    }

    var C config

    err := viper.Unmarshal(&C)
    if err != nil {
        log.Fatalln("unable to decode into struct, %v", err)
    }

    log.Println(C)
    log.Println(len(C.Languages))
}

未设置$MYPREFIX_LANGUAGES时,C.Languages的长度为2(例如默认值)。当我将$MYPREFIX_LANGUAGES设置为"英语西班牙语法语俄语"我得到的长度为1.它只是将变量作为1个长字符串,而不是切片。如何获得切片([]string{"english", "spanish", "french", "russian"}

1 个答案:

答案 0 :(得分:3)

感谢@Charlino,答案是:

package main

import (
    "log"

    "github.com/spf13/viper"
)

func main() {
    viper.SetEnvPrefix("myprefix")
    viper.SetTypeByDefaultValue(true)
    viper.SetDefault("languages", []string{"french", "spanish"})
    viper.BindEnv("name")
    viper.BindEnv("languages")

    type config struct {
        Name      string
        Languages []string
    }

    var C config

    err := viper.Unmarshal(&C)
    if err != nil {
        log.Fatalln("unable to decode into struct, %v", err)
    }

    log.Println(C)
    log.Println(len(C.Languages))
}