duanlongling5308 2016-07-29 11:00 采纳率: 0%
浏览 1303

在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?

  • 写回答

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 {
        confMux.Lock()
        defer confMux.Unlock()
        return configMap[name]
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效