- In this example, will the connection be closed or NO?
In this formulation of the problem - no, the connection will not be closed.
- As I understand it, the main function will not complete as long as ListenAndServe is running.
Yes, main will not complete. Moreover, it will not end in principle, since the only option to terminate the program after http.ListenAndServer (if you do not use additional libraries) is to send SIGTERM to it, after which it simply ends without worrying about the execution of the last directive from main . By the way, defer db.Close() will not work either, because main not completed.
- and you need to close the connection at the end of each HandleFunc?
The connection does not need to close at all. Inside db/sql connection pool is used , i.e. Once you db.SetMaxIdleConns and db.SetMaxOpenConns you can forget about managing connections.
If it is critical for you to close the connection, the only option is to intercept the commands for termination and close the connection. Code like this
imports ( ... _ "github.com/go-sql-driver/mysql" "os" "os/signal" "syscall" ) func main() { db, err := sql.Open(...) c := make(chan os.Signal, 2) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { <-c db.Close() os.Exit(1) }() http.HandleFunc("/", TestFunc) http.ListenAndServe(":8080", nil) }
But, again, in reality this is a useless exercise.