How to create global variables once when app is launched in Go?

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

How to create global variables once when app is launched in Go?

问题

大家好!

我有一个需要密钥进行解密的API服务。每次我发出请求时,密钥都会重新计算。从架构的角度来看,这是错误的。

使用环境变量(.env、viper等)的选项不适用,因为将来我想将这个模块拆分为一个独立的库。

请给我一些建议,如何在启动应用程序时计算密钥,并在停止应用程序之前一直使用它,而不使用环境变量?

英文:

Good day for all readers!

I have api service which needs key for some decrypt issues. Key calculates all time when I make request. That is wrong from an architectural point of view.

The option with environments (.env, viper...) drops because, in the future, I want to bring out this module to a separate library.

Hint me, how it is possible without using environments to calculate the key when starting the application and use it until stopping the application?

答案1

得分: 1

全局变量以大写字母开头,因此可以从其他包中访问。

但是...这实际上是不好的行为,因为其他包可以更改它。

如果使用非大写字母开头的变量,仍然意味着同一包中的函数可以更改它。

也许你可以使用常量?
或者创建一个单例变量,参见:

https://goplay.tools/snippet/9k7FLYbbvoo

英文:

A global var starts with a capital, so it is reachable from within other packages.

But... it's actually bad behaviour, because those other packages can change it.

Having a non capital one, still means that functions in the same package can change it.

Perhaps you can use a constant?
or make a singleton variable, see :

https://goplay.tools/snippet/9k7FLYbbvoo

答案2

得分: 0

如果你确定需要一个全局变量,你可以这样做:

package main

var globalVar string = "My string"

func init(){
	globalVar = "The new value of the variable"
}

func main(){
	println(globalVar)
}

英文:

If you are sure you need a global variable, you can do this:

package main

var globalVar string = "My string"

func init(){
	globalVar = "The new value of the variable"
}

func main(){
	println(globalVar)
}

huangapple
  • 本文由 发表于 2022年2月11日 19:30:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/71079389.html
匿名

发表评论

匿名网友

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

确定