I just started learning Go. Lesson of the day was to wrap my database handler in a struct to avoid using global scope variables. Thought I understood it so far and wanted to defer the Close() method as I did before, which ended in an stack overflow.
I couldn't find an explanation why this happen, nor what's the propper way to do this.
Here is the key code:
package exporter
type DB struct {
*sqlx.DB
queriesExecuted int
}
func Open(dataSourceName string) *DB {
connection := sqlx.MustConnect("mysql", dataSourceName)
db := &DB{connection, 0}
return db
}
func (db *DB) Close() {
db.Close() // this is where the stack growth happens
}
func (db *DB) GetArticles() []oxarticle {
...
}
package main
func main() {
exporter := feedexporter.Open("root:pass@/feedexport")
defer exporter.Close()
articles := exporter.GetArticles()
}
Everything works fine without the defer exporter.Close(), including it ends in:
runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow
It feels so bad to not close connections ;) What's the propper way to handle this?