I have a config object which initializes some variables based on environment variables at startup:
// init the conf object on startup and fail quickly if there's an environment issue
_ = utils.GetConf()
This is in the init() method of my server, and in other places in my code, I just call GetConf() to get the config object. I'd like to implement this config object through a singleton pattern:
import (
"fmt"
env "github.com/Netflix/go-env"
)
type Conf struct {
DBName string `env:"MONGO_INITDB_DATABASE,required=true"`
Hostname string `env:"HOSTNAME,required=true"`
DBUsername string `env:"MONGO_INITDB_ROOT_USERNAME,required=true"`
DBPassword string `env:"MONGO_INITDB_ROOT_PASSWORD,required=true"`
}
var gConf *Conf
func GetConf() *Conf {
if gConf != nil {
return gConf
}
gConf = new(Conf)
_, err := env.UnmarshalFromEnviron(gConf)
if err != nil {
panic(err)
}
return gConf
}
Since I'm not doing anything with the return value of utils.GetConf() at the start, is it possible that golang will garbage collect my config object and my gConf pointer will end up pointing to nowhere?