Where should I open the database connection?


(Anik Hasibul) #1

I am working on a web application in Golang. Where should I open my database? In main or in http.HandleFunc?

func main(){
    db, _ := sql.Open("driver",dbinfo)
    // other http.HandleFunc  goes here
}

or

func AHandler(w http.ResponseWriter, r *http.Request) {
     db, _ := sql.Open("driver",dbinfo)
      //it will open a new database connection for every new request!
}

(Norbert Melzer) #2

From the docs:

Thus, the Open function should be called just once.

This, you call it in the main and make its returned value globally available.