Is it a good idea to use global variables to store DB handles in a Go web application?

557 views
Skip to first unread message

alse...@gmail.com

unread,
Jul 8, 2014, 7:34:54 AM7/8/14
to golan...@googlegroups.com

Hello,

Official guide says it's okay to use a global variable to cache templates:

http://golang.org/doc/articles/wiki/

First we create a global variable named templates, and initialize it with ParseFiles.

Can global variables also be used to store DB handles and repository objects? Or do they have to be initialized for every request?

Thanks a lot

egon

unread,
Jul 8, 2014, 12:26:12 PM7/8/14
to golan...@googlegroups.com, alse...@gmail.com
It depends. Global variables make testing harder and it couples things more together. Then again sometimes a global variable is easier to manage rather than passing it around everywhere. The only thing you need to be aware of are race conditions.

Basically, if it's something important, don't use global variables. If it isn't important, you'll get things done faster with global variables and with some locks.

+ egon

Siddon Tang

unread,
Jul 8, 2014, 11:34:39 PM7/8/14
to golan...@googlegroups.com
For go database handle, it is safe for concurrent, see http://golang.org/pkg/database/sql/#Open, so  you can use it as global which must be initialized first at somewhere certainly. 

I like write a http handle holds the db pointer. e.g. 

type MyHandle struct {
    db *sql.DB
}
func (h *MyHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
     //use h.db here
}
func main() {
    db := sql.Open(dsn)
    h := &MyHandle{db}
    http.Handle("/", h)
}


在 2014年7月8日星期二UTC+8下午7时34分54秒,alse...@gmail.com写道:
Reply all
Reply to author
Forward
0 new messages