从另一个函数创建全局变量

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

Make global variable from another func

问题

如何创建全局的 JSON 配置并在任何地方使用它?

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. )
  8. // Config 结构体用于存储配置信息
  9. type Config struct {
  10. Keywords string `json:"Keywords"`
  11. }
  12. var config Config // 全局变量用于存储配置
  13. func indexHandler(w http.ResponseWriter, r *http.Request) {
  14. // 使用配置
  15. fmt.Println(config.Keywords) // <-- 在这里使用
  16. }
  17. func main() {
  18. // 初始化配置
  19. config = loadConfig()
  20. // 打印配置信息
  21. fmt.Println(config.Keywords) // 这里会输出 "keywords1" - 正确
  22. // 路由
  23. http.HandleFunc("/", indexHandler)
  24. // 获取端口
  25. http.ListenAndServe(":3000", nil)
  26. }
  27. // loadConfig 函数用于加载配置文件
  28. func loadConfig() Config {
  29. file, err := ioutil.ReadFile("config.json")
  30. if err != nil {
  31. panic(err)
  32. }
  33. var config Config
  34. err = json.Unmarshal(file, &config)
  35. if err != nil {
  36. panic(err)
  37. }
  38. return config
  39. }

完整代码:https://gist.github.com/liamka/15eec829d516da4cb511

在上面的代码中,我们创建了一个 Config 结构体来存储配置信息,并声明了一个全局变量 config 来保存配置。在 main 函数中,我们通过调用 loadConfig 函数来加载配置文件,并将返回的配置赋值给全局变量 config。然后,在 indexHandler 函数中,我们可以直接使用 config.Keywords 来访问配置信息。

英文:

How make global json config and use it everywhere?

  1. func indexHandler(w http.ResponseWriter, r *http.Request) {
  2. // Use config
  3. fmt.Println(config[&quot;Keywords&quot;]) // &lt;-- USE HERE
  4. }
  5. func main() {
  6. config := models.Conf() // Init there!
  7. fmt.Println(config.Keywords) // This prints &quot;keywords1&quot; - good
  8. // Routes
  9. http.HandleFunc(&quot;/&quot;, indexHandler)
  10. // Get port
  11. http.ListenAndServe(&quot;:3000&quot;, nil)
  12. }

Full code: https://gist.github.com/liamka/15eec829d516da4cb511

答案1

得分: 2

问题很简单,就是在主函数中你创建了一个新的config实例,而不是使用全局变量。

你的代码如下:

  1. var config map[string]*models.Config

这是全局变量。而在main函数中你有:

  1. func main() {
  2. config := models.Conf()
  3. ...

这创建了一个局部变量并将其丢弃。你需要做的是:

全局变量:

  1. var config models.Config

在main函数中:

  1. func main() {
  2. config = models.Conf()
  3. ...

这样将引用全局变量而不是局部变量。

英文:

The problem is simply that in main you create a new config instance instead of using the global variable

You have:

  1. var config map[string]*models.Config

Which is the global var. and in main() you have:

  1. func main() {
  2. config := models.Conf()
  3. ...

which creates a local variable and throws it away. This is what you need to do:

The global var:

  1. var config models.Config

In main:

  1. func main() {
  2. config = models.Conf()
  3. ...

this will reference the global variable and not the local one.

huangapple
  • 本文由 发表于 2015年7月30日 19:52:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/31723063.html
匿名

发表评论

匿名网友

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

确定