2

I'm using viper package to load config from file. My config file look like this:

/// config.yml

server: &server
  name: "Test Server"
  host: localhost
  port: 8084

database:
  drivers:
    mysql: &mysql
      driver: mysql
      host: ${MY_HOST_VARIABLE_HERE}
      username: ${MY_USERNAME_VARIABLE_HERE}
      password: ${MY_PASSWORD_VARIABLE_HERE}
      dbname: ${MY_DATABASE_VARIABLE_HERE}
      port: 3306
    postgres: &postgres
      driver: postgres
      host: ${MY_HOST_VARIABLE_HERE}
      username: ${MY_USERNAME_VARIABLE_HERE}
      password: ${MY_PASSWORD_VARIABLE_HERE}
      dbname: ${MY_DATABASE_VARIABLE_HERE}
      port: 5432

I want to config the secret variables like database name, database username, database user password... into the environment variables. With another normal variables, i can config direct in this file, it doesn't matter. This is my code:

viper.AddConfigPath(".")
viper.SetConfigType("yaml")

viper.AutomaticEnv()

if err := viper.ReadInConfig(); err != nil {
  log.Fatal(err)
}

var cfg Config

if err := viper.Unmarshal(&cfg); err != nil {
  log.Fatal(err)
}

And this is my .env

MY_HOST_VARIABLE_HERE=localhost
MY_USERNAME_VARIABLE_HERE=test
MY_PASSWORD_VARIABLE_HERE=test
MY_DATABASE_VARIABLE_HERE=test

But it doesn't working, i can't read yaml and env config in the same time. Database name or username... is undefined. Somebody can help me?

Dean
  • 415
  • 1
  • 5
  • 15

1 Answers1

0

Please set the name of config file by below code,

viper.SetConfigName("config")

Add the above code in first line.

0xRyN
  • 852
  • 2
  • 13
  • Ah yes of course. viper.SetConfigName("config") viper.AddConfigPath(".") viper.SetConfigType("yaml") – Dean Nov 30 '22 at 17:29