spf13 / viper

Go configuration with fangs
MIT License
26.88k stars 2.01k forks source link

Retrieve value in different package then the one reading the config file #216

Open ChristianAE opened 8 years ago

ChristianAE commented 8 years ago

In my main.go file I placed the code to read the config file. In the main package (main.go) I can read from the config without any issues. When I use the same code in a different package (storage/storage.go) the value is empty. Is there a way to make the config read in the main package available to other packages?

Reading the config:

func initConfig() {
    log.Println("Initialize config")
    viper.SetConfigName("config")
    viper.AddConfigPath("./templates")
    if err := viper.ReadInConfig(); err != nil {
        log.Panic(err)
    }
    log.Println("Config successfully initialized")
}

Reading from the config: port := viper.GetString("port")

Structure of the project:

templates
  --storage.go
main.go

config.json:

{
  "port": 8181
}
saprakashh commented 6 years ago

I am facing the same issue. This is preventing me from modularizing my code.

navid-kalaei commented 4 years ago

One approach is to make your config setter return an instance of viper, then use that returned object whenever you want to read the config. However if you are concerned about reading the config file multiple times when calling the config setter, the factory pattern would be useful. Eighter viper.GetViper and viper.New returns instances of viper and sync.Once is beneficial for the factory patter.

cyrmax commented 2 months ago

I've come here with the same question as the topic starter. As the problem is solved even with two different aproaches, probably it's a time to close this issue? @ChristianAE What do you think about it?