dongshenchi5364 2018-08-31 11:45
浏览 81
已采纳

如何在GO中处理全局状态

I recently joined a project where there's an external configuration style service - basically a KV store that's called with jsonrpc.

Don't ask why it's there..

I need to query this config service to obtain a whitelist used internally within the codebase.

However, I can't come to a solution without using a global var. For example I call a function to get the config from package A but must export the var for it to be used within other packages. My original solution was to use gocache setting the cache within a package and exporting the cache accessor to have some type restriction. However, this added complexity and seemed too much rather than just storing the val in an exported var.

I have seen global vars used within the standard library but am confused as this would go against the law of encapsulation?

Would appreciate any advice how to approach a problem like this.

  • 写回答

1条回答 默认 最新

  • doulanyan6455 2018-08-31 12:47
    关注

    If your project is small or is not expected to change much, then a global config could be okay. I’d put the config variable in a package of its own though. On the other hand, if the project is expected grow over time, it makes sense to have things encapsulated.

    Can you pass the config as a parameter from package A to any other package that needs it in the form of method or constructor args? I think passing things around makes the dependency on the config obvious and also allows for easier mocking in tests.

    Personally I'd structure the project like this (if i was working from scratch - probably not a luxury you have):

    project root
    |
    |- config/
    |  |- Config (interface) -> knows how to fetch config form JSON-RPC and caches it if necessary
    |  |  |- GetSomething1()
    |  |  |- GetSomething2()
    |  |  |- Get(key string) -> If you have arbitrary keys
    |  |
    |  |- NewJsonRpcConfig(settings) -> returns something that implements the Config interface
    |
    |- main.go -> calls config.NewConfig()
       |
       |- Passes the resulting Config interface as a parameter to anything that needs it.
          Packages don't directly interact with a global variable.
    

    All the config stuff is in the config package. It can talk to the JSON-RPC server, maybe cache the results and return the config. The main package creates an instance of the config fetcher and passes it to all instances that need to use the config.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助