2016-07-29 11:00
采纳率: 0%
浏览 1.0k



// 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{


图片转代码服务由CSDN问答提供 功能建议


func main(){
 router:= routers.InitApp()
 router.RunTLS(“:9000”,“ domain.crt”,“ domain.key”)


var ConfigMap = GetAppConfig 
func GetAppConfig()映射[ 字符串] string {
 .... // 

ConfigMap是全局变量,每次我尝试访问 utils.ConfigMap < / code>映射 GetAppConfig 函数。 在应用程序初始化时,我如何才能只调用一次此函数,然后在go项目中我想要的任何位置访问ConfigMap。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dta25920 2016-07-29 11:03

    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 {
        defer confMux.Unlock()
        return configMap[name]
    打赏 评论
  • drox90250557 2016-07-30 02:11

    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.

    打赏 评论

相关推荐 更多相似问题