Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read config using a struct #607

Closed
spy16 opened this issue Dec 9, 2018 · 4 comments
Closed

Read config using a struct #607

spy16 opened this issue Dec 9, 2018 · 4 comments

Comments

@spy16
Copy link

spy16 commented Dec 9, 2018

Is there a way to directly register a struct with viper and read configs appropriately ?

Something like demonstrated below:

type config struct {
   Host string
   Port int
   Database database
}

type database struct {
   Host string
   Port int
}

cfg := config{
     Host: "localhost",
     Port: 8080,
}
viper.AutomaticEnv()
viper.SetConfigName("app")
viper.ReadInConfig()
viper.Unmarshal(&cfg)

I know Unmarshal exists but it doesn't do what i was expecting. My expectation for the above snippet was that, after the Unmarshal call, following would be true:

  1. cfg.Host would be mapped to HOST env var, or host key in app.yaml or app.json etc.
  2. cfg.Database.Host would be mapped to DATABASE_HOST env var, database_host key in app.yaml or app.json etc (or host sub-key of database key in these files)
  3. Non-zero values given to the fields will be used as defaults if an overriding value not found in any config source (i.e., env var, yaml files, json files etc.)

Why?

One of the projects i am working which is using viper has has large set of configuration options. It is becoming tedious to add viper.GetString("config_name") for every single config and then populate the config struct. If the above expectations were true, we could simply compose configs of different structs into one config struct and call Unmarshal with that struct.

@Nicolab
Copy link

Nicolab commented Jan 26, 2019

I have the same, you are found a solution?

@sagikazarmark
Copy link
Collaborator

Looks like a duplicate of #584

See my comment: #584 (comment)

TL;DR Unmarshal doesn't work with AutomaticEnv.

@Nicolab
Copy link

Nicolab commented Jan 27, 2019

Thanks

@spy16
Copy link
Author

spy16 commented Jan 29, 2019

Okay thanks @sagikazarmark . Will close this in favor of discussion on #584.

@spy16 spy16 closed this as completed Jan 29, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants