Home > Software engineering >  How to save Env variable persistently
How to save Env variable persistently

Time:05-05

When the service starts, a session key is generated and I try to put it in an environment variable to use in the future (also when restarting the service).

I used os.Setenv() for this, but after restarting, the environment variable is empty.

sessionKey := os.Getenv(_sessionKey)
if sessionKey == "" {
  sessionKey = string(securecookie.GenerateRandomKey(32))
  os.Setenv(_sessionKey, sessionKey)
}
sessionsStore := sessions.NewCookieStore([]byte(sessionKey))

Is there another way to use environment variables for this purpose, or it's better to save it to a file?

CodePudding user response:

Used 'viper' lib to save env variables to the file:

func Getenv(key string) string {
    viper.SetConfigType("env")
    viper.SetConfigFile(".env")

    err := viper.ReadInConfig()
    if err != nil {
        log.Fatalf("Error while reading config file %s", err)
    }

    value, ok := viper.Get(key).(string)
    if !ok {
        return ""
    }

    return value
}

func Setenv(key string, value string) {
    viper.SetConfigType("env")
    viper.SetConfigFile(".env")

    err := viper.ReadInConfig()
    if err != nil {
        log.Fatalf("Error while reading config file %s", err)
    }

    viper.Set(key, value)

    err = viper.WriteConfig()
    if err != nil {
        log.Fatalf("Error while writing config file %s", err)
    }
}
  • Related