Issue
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?
Solution
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)
}
}
Answered By - Darusolog Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.