英文:
Make global variable from another func
问题
如何创建全局的 JSON 配置并在任何地方使用它?
package main
import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)
// Config 结构体用于存储配置信息
type Config struct {
	Keywords string `json:"Keywords"`
}
var config Config // 全局变量用于存储配置
func indexHandler(w http.ResponseWriter, r *http.Request) {
	// 使用配置
	fmt.Println(config.Keywords) // <-- 在这里使用
}
func main() {
	// 初始化配置
	config = loadConfig()
	// 打印配置信息
	fmt.Println(config.Keywords) // 这里会输出 "keywords1" - 正确
	// 路由
	http.HandleFunc("/", indexHandler)
	// 获取端口
	http.ListenAndServe(":3000", nil)
}
// loadConfig 函数用于加载配置文件
func loadConfig() Config {
	file, err := ioutil.ReadFile("config.json")
	if err != nil {
		panic(err)
	}
	var config Config
	err = json.Unmarshal(file, &config)
	if err != nil {
		panic(err)
	}
	return config
}
完整代码:https://gist.github.com/liamka/15eec829d516da4cb511
在上面的代码中,我们创建了一个 Config 结构体来存储配置信息,并声明了一个全局变量 config 来保存配置。在 main 函数中,我们通过调用 loadConfig 函数来加载配置文件,并将返回的配置赋值给全局变量 config。然后,在 indexHandler 函数中,我们可以直接使用 config.Keywords 来访问配置信息。
英文:
How make global json config and use it everywhere?
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)
}
Full code: https://gist.github.com/liamka/15eec829d516da4cb511
答案1
得分: 2
问题很简单,就是在主函数中你创建了一个新的config实例,而不是使用全局变量。
你的代码如下:
var config map[string]*models.Config
这是全局变量。而在main函数中你有:
func main() {
config := models.Conf()
...
这创建了一个局部变量并将其丢弃。你需要做的是:
全局变量:
var config models.Config
在main函数中:
func main() {
config = models.Conf()
...
这样将引用全局变量而不是局部变量。
英文:
The problem is simply that in main you create a new config instance instead of using the global variable
You have:
var config map[string]*models.Config
Which is the global var. and in main() you have:
func main() {
config := models.Conf()
...
which creates a local variable and throws it away. This is what you need to do:
The global var:
var config models.Config
In main:
func main() {
config = models.Conf()
...
this will reference the global variable and not the local one.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论