简体   繁体   English

Golang访问共享连接资源的最佳实践?

[英]Golang best practice to access shared connection resources?

What is the best practice for handling scope with dealing with shared connection resources to outside services in golang (RabbitMQ, database, etc)? 在golang(RabbitMQ,数据库等)中处理外部服务的共享连接资源来处理范围的最佳实践是什么? For example, given this code using database/sql, pq, and http: 例如,给定此代码使用database / sql,pq和http:

func main() {
    db, err := sql.Open("postgres", "user=root dbname=root")
        if err != nil {
        log.Fatal(err)
    }

    http.HandleFunc("/", front_handler)
    http.HandleFunc("/get", get_handler)
    http.HandleFunc("/set", set_handler)
    http.ListenAndServe(":8080", nil)
}

What's the best way to make the db object available to my registered handlers? 使db对象可用于我的注册处理程序的最佳方法是什么?

Do I put the db declaration outside the main scope (this would cause me unit testing problems in Python but might be okay here)? 我是否将db声明放在主范围之外(这会导致我在Python中进行单元测试问题但在这里可能没问题)?

Do I put the handler declarations inside the main scope (it doesn't seem like I'm allowed to nest functions)? 我是否将处理程序声明放在主作用域内(似乎我不允许嵌套函数)?

Is there an addressing scheme I can use to access the main scope (I'd do something like that in puppet)? 有没有我可以用来访问主范围的寻址方案(我会在木偶中做类似的事情)?

Some other option? 还有其他选择吗?

There's a lot of ways you could deal with this. 有很多方法可以解决这个问题。 Firstly, having opened the connection in this scope, you probably want to defer it's close here. 首先,在此范围内打开连接后,您可能希望将其推迟到此处。

db, err := sql.Open("postgres", "user=root dbname=root")
        if err != nil {
        log.Fatal(err)
    }
defer db.Close()

Which will ensure the connection gets cleaned up when you're leaving this scope. 当您离开此范围时,这将确保连接得到清理。 Regarding your handlers... It would be simple to write them as closures in the same scope as the connection so you can use it freely. 关于你的处理程序......将它们作为闭包写在与连接相同的范围内是很简单的,这样你就可以自由地使用它。

EDIT: To clarify, you said you don't think you can nest functions in main. 编辑:澄清一下,你说你不认为你可以在main中嵌套函数。 You can do this with something like; 你可以这样做;

get_handler := func() {
      return db.ReadTheData()
}
http.HandleFunc("get", get_handler)

It's common for most apps to start out with the DB handler at the global scope. 大多数应用程序通常在全局范围内使用数据库处理程序。 sql.DB is defined to be safe for concurrent access, and therefor can be simultaneously used by all handlers that need it. sql.DB被定义为对于并发访问是安全的,因此所有需要它的处理程序可以同时使用它。

var db *sql.DB

func main() {
    var err error
    db, err = sql.Open("postgres", "user=root dbname=root")
    if err != nil {
        log.Fatal(err)
    }
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM