在golang中仅设置一次全局变量

我有一个main.go文件:

// running the router in port 9000
func main() {
    router := routers.InitApp()
    router.RunTLS(":9000" , "domain.crt" , "domain.key")
}

在另一个文件里:

package utils
var ConfigMap = GetAppConfig
func GetAppConfig() map[string]string{
 ....//
}

ConfigMap是一个全局变量,每当我尝试访问utils.ConfigMap映射时,都会调用GetAppConfig函数。在GO项目中,如何在不初始化应用程序的情况下,调用此函数访问ConfigMap?

This is what package init() functions are for. They are executed once, before your package can be reached "from the outside":

var ConfigMap map[string]string

func init() {
    // Init ConfigMap here
}

Note that such exported global variables should be protected if you want to allow concurrent use. It would be unfeasible to leave this to the users of the package.

For this purpose, you should declare ConfigMap unexported:

var configMap[string]string

And provide a getter function which would properly protect it with a Mutex:

var confMux = &sync.Mutex{}

func Config(name string) string {
    confMux.Lock()
    defer confMux.Unlock()
    return configMap[name]
}

I believe there is a typo in the code that you posted. You define the configMap outside the init function like this:

var configMap map[string]string

This is fine but inside the init you also have this:

var configMap = map[string]string{}

Here you are shadowing the configMap that you have outside the init function meaning that you have declared the variable again inside the init. As a result when you access the variable outside of the init function you will get the global variable which is still empty. If you remove the var inside the init it would work fine.

configMap = map[string]string{}

Here's a quick demonstration.

There is another typo in the original question:

var configMap = GetAppConfig

This should be:

var configMap = GetAppConfig()

You are assigning the function to a variable rather than result of the function.