gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:33:24 25 4
gpt4 key购买 nike

如何制作全局 json 配置并在任何地方使用它?

func indexHandler(w http.ResponseWriter, r *http.Request) {
// Use config
fmt.Println(config["Keywords"]) // <-- USE HERE
}

func main() {
config := models.Conf() // Init there!
fmt.Println(config.Keywords) // This prints "keywords1" - good

// Routes
http.HandleFunc("/", indexHandler)

// Get port
http.ListenAndServe(":3000", nil)
}

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

最佳答案

问题很简单,在 main 中你创建了一个新的配置实例,而不是使用全局变量

你有:

var config map[string]*models.Config

这是全局变量。在 main() 中你有:

func main() {

config := models.Conf()
...

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

全局变量:

var config models.Config

主要内容:

func main() {

config = models.Conf()
...

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

关于json - 从另一个函数创建全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31723063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com