There is no authoritative answer, as it depends on the driver you're using. If you're using either:
... then you shouldn't close your sql.DB
at all. The sql.DB
in those cases represents a connection pool, and using it in your handlers/requests/functions means you are just using a connection from that pool (if available).
e.g.
var db *sql.DB
func setup() error {
var err error
db, err = sql.Open(...)
if err != nil {
log.Fatal(err)
}
// Other setup-related activities
}
func main()
err := setup()
if err != nil {
log.Fatal(err)
}
// No need to call `defer db.Close()` here
http.ListenAndServe(...)
}
func SomeHandler(w http.ResponseWriter, r *http.Request) {
u := User{}
res, err := db.GetThings(&u)
// No need to close this here - it's just a connection dynamically pulled
// from our sql.DB connection pool in most cases
}