How to save Env variable persistently

huangapple go评论64阅读模式
英文:

How to save Env variable persistently

问题

当服务启动时,会生成一个会话密钥,并尝试将其放入环境变量中以供将来使用(包括在重新启动服务时)。我使用了*os.Setenv()*来实现这一点,但在重新启动后,环境变量为空。

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

是否有其他方法可以用于此目的的环境变量,或者将其保存到文件中更好?

英文:

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.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

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

答案1

得分: 1

使用'viper'库将环境变量保存到文件中:

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

    err := viper.ReadInConfig()
    if err != nil {
        log.Fatalf("读取配置文件时发生错误:%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("读取配置文件时发生错误:%s", err)
    }

    viper.Set(key, value)

    err = viper.WriteConfig()
    if err != nil {
        log.Fatalf("写入配置文件时发生错误:%s", err)
    }
}

以上是使用'viper'库将环境变量保存到文件的代码。

英文:

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

func Getenv(key string) string {
	viper.SetConfigType(&quot;env&quot;)
	viper.SetConfigFile(&quot;.env&quot;)

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

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

	return value
}

func Setenv(key string, value string) {
	viper.SetConfigType(&quot;env&quot;)
	viper.SetConfigFile(&quot;.env&quot;)

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

	viper.Set(key, value)

	err = viper.WriteConfig()
	if err != nil {
		log.Fatalf(&quot;Error while writing config file %s&quot;, err)
	}
}

huangapple
  • 本文由 发表于 2022年5月1日 17:03:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/72075362.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定