When should you close the database connection in this simple web application?

I am writing a simple Go web application using PostgreSQL. My main function looks like

 var db *sql.DB func main() { var err error db, err = sql.Open("postgres", "...") if err != nil { log.Fatalf("Couldn't connect to the database: %v", err) } http.HandleFunc("/whatever", whateverHandler) http.ListenAndServe("127.0.0.1:8080", nil) } 

It seems like I should call Close() in a database connection at some point, but when? This application works forever (i.e. until I kill it with ^C ). If I put the code after calling ListenAndServe , it will not run because my ^C killed the whole application. Should my application be structured differently?

+6
source share
2 answers

In this particular case, I am inclined to say that you do not even need to worry: the connection will be closed when the program ends, so you will not miss anything.

If you really need to close things correctly, it's easier to choose a graceful server, and defer to close resources.

Or, if your use case is more complicated, do it manually, catching the signals and gracefully closing your own path (using the closing channel, for example).

+5
source

It is important to understand that sql.Open() does not open a connection to the database ... http://golang.org/pkg/database/sql/#Open

Open can simply test its arguments without creating a database connection. To verify that the data source name is correct, call Ping.

It is also important to understand that the driver manages connection maintenance. Thus, you probably want to leave it open for the rest of your application life.

The returned database is safe for simultaneous use by several goroutines and supports its own connection idle pool. Therefore, the Open function should be called only once. It is extremely rare to close the database.

+1
source

Source: https://habr.com/ru/post/983824/


All Articles