PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 19, 2022

[FIXED] How to save Env variable persistently

 August 19, 2022     bash, environment-variables, go     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing