title: Viper mapping environment variable to struct member
body: <p>Here's my <code>config.yaml</code> file</p>
  <pre><code>server:
    port: 5000
  </code></pre>
  <p>here's my logic to unmarshal using viper</p>
  <pre><code>type Configurations struct {
      Server ServerConfig
  }
  
  type ServerConfig struct {
      Port int
  }
  
  // LoadConfig reads configuration from file or environment variables.
  func LoadConfig(path string) (config Configurations, err error) {
      viper.AddConfigPath(path)
      viper.SetConfigName(&quot;config&quot;)
      viper.SetConfigType(&quot;yaml&quot;)
  
      viper.AutomaticEnv()
  
      err = viper.ReadInConfig()
      if err != nil {
          return
      }
  
      err = viper.Unmarshal(&amp;config)
      return
  }
  </code></pre>
  <p>I have set env variable <code>export PORT=9000</code>, now my question is how can I map the environmental variable <code>PORT</code> to <code>Configurations.ServerConfig.Port</code>.
  I would like to have config file with default values for dev and would like my app to read/override config from env variables on production, how can I achieve this using viper.</p>
  <p>I see following options</p>
  <ol>
  <li>set <code>SERVER_PORT</code> and then use replacer like below to unmarshal it to struct</li>
  </ol>
  <pre><code>replacer := strings.NewReplacer(&quot;.&quot;, &quot;_&quot;)
  viper.SetEnvKeyReplacer(replacer)
  </code></pre>
  <ol start="2">
  <li><a href="https://stackoverflow.com/questions/52756532/go-viper-yaml-values-environment-variables-override">Go viper .yaml values environment variables override</a></li>
  </ol>
  <p>But I would like to map variable <code>PORT</code> to the struct member, probably because my hosting service provider sets <code>PORT</code> env variable, and I cannot use 2nd point because I would like to have yaml for default values.</p>