Skip to content

Unmarshal() does not use the env variable if the config file has no that key #1236

@zzycn003

Description

@zzycn003

Preflight Checklist

  • I have searched the issue tracker for an issue that matches the one I want to file, without success.
  • I am not looking for support or already pursued the available support channels without success.

Viper Version

1.9.0

Go Version

1.16

Config Source

Environment variables, Files

Format

YAML

Repl.it link

No response

Code reproducing the issue

type Redis struct {
   Addrs string `mapstructure:"addrs"`
   PoolSize int `mapstructure:"poolSize"`
}

var (
	cfgFile string
	cfg     Redis
)

// the config file as below
/**
{
  "addrs": "127.0.0.1:6379"
  // NOTE: the config file does not contains the key for poolSize, poolSize is injected from env
}
*/

/**
  env is POOLSIZE=100
*/

func main() {
       
	viper.SetConfigFile(cfgFile)
	viper.AutomaticEnv()
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

	if err := viper.ReadInConfig(); err != nil {
		return fmt.Errorf("failed to load config file %s: %v", cfgFile, err)
	}
	if err := viper.Unmarshal(&cfg); err != nil {
		return fmt.Errorf("failed to marshal config file %s: %v", cfgFile, err)
	}
}

Expected Behavior

cfg.PoolSize == 100

Actual Behavior

cfg.PoolSize == 0

Steps To Reproduce

  1. with config file, has no a key for poolSize
  2. the poolSize is injected with environment
  3. call viperh.Unmarshal

NOTE: only when the poolSize is defined in config file, the env override works

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions