My golang main()
routing initializes a db connection and then passes it to another function to start the main processing.
func main() {
dbinfo := fmt.Sprintf("user=%s dbname=%s sslmode=disable", "my_user", "my_db")
db, err := sql.Connect("postgres", dbinfo)
if err != nil { log.Fatalln(err) }
defer db.Close()
model.Run(db)
}
The model.Run()
method goes off to call several other packages and functions, and just passes the db
object around between them.
What if one of those various downstream functions run into an error? Will the program just shut down without closing my connection defined above? Or will it bubble up the exception and execute my defer
statement in main()
?
For what it's worth, I'm handling all errors as follows -
_, err := someFunction()
if err != nil { log.Fatalln(err) }
Note: Fatalln
is equivalent to calling Println
and then os.Exit(1)
(See here)