简体   繁体   English

viper 不会从 env 或 pflags 解组值

[英]viper does not unmarshal values neither from env or pflags

I have the following very simple go program我有以下非常简单的go程序

package main

import (
    "fmt"

    "github.com/spf13/cobra"
    "github.com/spf13/viper"
)

type Config struct {
    AFlag string `mapstructure:"A_FLAG"`
}

var rootCmd = &cobra.Command{
    Use:   "myapp",
    Short: "My app",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("running")
    },
}

func InitConfig(cmd *cobra.Command) {
    var conf Config
    v := viper.New()
    v.AddConfigPath(".")
    v.SetConfigName(".env")
    v.SetConfigType("env")
    v.SetEnvPrefix("FOO")
    v.AllowEmptyEnv(true)
    v.AutomaticEnv()
    v.BindPFlags(cmd.Flags())
    v.Unmarshal(&conf)
    fmt.Printf("%+v\n", conf)
}

func main() {
    rootCmd.PersistentFlags().StringP("a-flag", "", "", "a flag")
    InitConfig(rootCmd)
    rootCmd.Execute()
}

after

export FOO_A_FLAG=test

or either running as或运行为

go run main.go --a-flag=test

the program should be printing该程序应该正在打印

{AFlag:test}
running

However it seems it does not take into account the env var (with the prefix) nor the flag但是,它似乎没有考虑到 env var(带前缀)和标志

{AFlag:}
running

Try this尝试这个

viper.SetConfigName("local")
    viper.SetConfigType(".env")
    viper.AddConfigPath("./config")     
    if err := viper.ReadInConfig(); err != nil {
        panic(ErrorsWrap(err, "error occured while reading env file"))
    }
    if err := viper.Unmarshal(&Env); err != nil {
        panic(ErrorsWrap(err, "error occured while unmarshalling env data"))
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM