1

I am using viper for reading config files in my go module.

Tree structure;

.
├── README.md
├── package1
│   └── package1.go
├── config.json
├── helper
│   └── helper.go
└── main.go

I initialized Viper in my main.go

    viper.SetConfigFile("config.json")
    viper.AddConfigPath(".")
    err := viper.ReadInConfig() 
    if err != nil {             
        panic(fmt.Errorf("fatal error config file: %w", err))
    }

Now I can get keys with viper.GetString("key"), everything works fine.

But if In package1.go I do viper.GetString("key") I get empty string(no value).

I had to initialize Viper in package1.go with SetConfigFile and AddConfigPathto make it work.

I dont feel this is the right way, what am I doing wrong?

Nagri
  • 3,008
  • 5
  • 34
  • 63
  • If `package1.go` is a standalone package, the path to config.json should be `.. /config.json`. Otherwise, you don't need to initialize viper in each package. It only needs to be initialized in the startup entry of the entire program. – Trock Aug 29 '23 at 06:50
  • Its not a standalone package. I am doing something wrong. – Nagri Aug 29 '23 at 06:53
  • *"what am I doing wrong?"* -- Most likely the order of execution is wrong. Make sure that `package1` is imported by `main` and make sure that the `viper` initialization in `main` is done *__before__* any code in `package1` that depends on `viper` is executed. – mkopriva Aug 29 '23 at 07:51
  • @mkopriva made sure of this. still have to reinitialize viper in package1 – Nagri Aug 29 '23 at 08:20
  • "made sure of this" ... Can you show how? – mkopriva Aug 29 '23 at 08:42

0 Answers0