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]
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名