如何在Go语言中在不同的包之间共享变量

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

How to share variables across packages in go-lang

问题

我已经写了一个简单的Go应用程序,并将其格式化为几个包。

+main
+controllers
+handlers
+commons
+utils

我在main包中启动服务器并在启动时读取服务器特定的参数。

我想要在commons包中使用这些参数,例如DB属性。但是我不能将main包导入到commons包中,因为commons是controllers和handlers的依赖项,而它们又是main的依赖项。这会导致循环导入。

我们应该如何处理这种情况?是否可以在读取配置时只读取一次,并在commons包中需要时引用它?能否提供一个示例?

英文:

I have written a simple go application and formatted it in to several packages.

+main
+controllers
+handlers
+commons
+utils

I'm starting the server in main package and reading server specific parameters at the startup.

I won't to use those parameters, such as DB properties from commons package. I cannot import main package in to commons 'cause commons is a dependency to controllers, handlers which is a dependency to main. So this causes cyclic import.

How should we handle this kind of situation?. Is it possible to read the configuration once and refer to it inside commons package whenever needed? Example would be helpful.

答案1

得分: 1

你可以使用一个配置包,在需要使用配置变量时,可以将其发送到不同包中的另一个结构体。

main() {
    config := config{}
    user = NewUser(config)
    ...
}

我建议你检查一下 config revel 包(https://github.com/revel/config)。它被用在 revel 框架中(https://github.com/revel/revel)。

英文:

You can use a config package and when you need to use a config variable then you can send to another struct into different package.

main() {
    config := config{}
    user = NewUser(config)
    ...
}

I recommend to you check the config revel package (https://github.com/revel/config). It's used into revel framework https://github.com/revel/revel.

huangapple
  • 本文由 发表于 2015年10月6日 21:13:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/32970957.html
匿名

发表评论

匿名网友

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

确定