Where should I open the database connection?

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


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

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.

1 Like