1

I have the following very simple go program

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

{AFlag:}
running
pkaramol
  • 16,451
  • 43
  • 149
  • 324

2 Answers2

0

I think you are exporting wrong env variable. Try using: export A_FLAG=test instead.

You may refer to the below link for some reference:

https://renehernandez.io/snippets/bind-environment-variables-to-config-struct-with-viper/

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 29 '23 at 01:14
-1

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"))
    }
  • This answer contains many details with no justification. For instance, the many `viper.AddConfigPath` calls are obscure -- and why do we need exactly 3 of them? It also reads as a *solution* rather than an *answer*: as a poster, I would have trouble understanding what I did wrong. – ariels May 30 '22 at 11:48