douliedai4838 2017-05-09 20:34
浏览 145

如何在Golang中共享服务连接

I'm new to Go and looking at this the elastic library for go and in the Getting Started example it says "You typically create one client for your app."

What does that mean? Do you create a client in the your main function and somehow pass it to the functions with context? Do you create a global variable and assign it to the client, like this?

var (
  client *elastic.Client
)

func a() {
  client.Search()
}

func main() {
  c, err := elastic.NewClient()
  client = c
}
  • 写回答

2条回答 默认 最新

  • dongmu3457 2017-05-09 21:07
    关注

    This gets into a topic that is kinda controversial in go: dependency injection.

    Unlike some other languages, we don't usually believe in complicated IOC containers, xml config, and reflection based tools for this kind of thing. I merely follow a few simple principles:

    1. Application packages and components should have all of their dependencies passed to them explicitly. Preferably as an interface type. If my web package needs a database connection, and an elastic client, it may have a function like Serve(addr string, db database.DB, client *elastic.Client) where DB is an interface type for my application's db.
    2. The job of main is essentially to read configuration, create all shared components, and pass them to the various components:

      func main(){
        var config = readConfig() //flags, json, whatever
        var elastic = elastic.NewClient(config.whatever)
        var db = database.New(config.Connectionstring)
      
        //now start app components
        web.Serve(config.Addr, db, elastic)
      }
      

    I find this pattern helps keep my packages separate yet inter-operable. I try to avoid package level variables for anything that needs to change from run to run.

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀