I have trouble with my current works. I build an apps using beego framework, Im new in golang.
First, I build other package called utils, and from that package I write some codes to access to my databases
func InitFirebird() {
var (
dbDriver = beego.AppConfig.String("DB_CONNECTION")
dbUsername = beego.AppConfig.String("DB_USERNAME")
dbPassword = beego.AppConfig.String("DB_PASSWORD")
dbServer = beego.AppConfig.String("DB_HOST")
// dbPort = beego.AppConfig.String("DB_PORT")
dbFileName = beego.AppConfig.String("DB_DATABASE")
)
conn, _ := sql.Open(dbDriver, dbUsername+":"+dbPassword+"@"+dbServer+"/"+dbFileName)
defer conn.Close()
}
After that, I go to my main.go and setting up my init function and main function like this:
func init() {
utils.InitFirebird()
}
func main() {
if beego.BConfig.RunMode == "dev" {
beego.BConfig.WebConfig.DirectoryIndex = true
beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
}
var n int
conn.QueryRow("SELECT Count(*) FROM rdb$relations").Scan(&n)
fmt.Println("Relations count=", n)
beego.Run()
}
When I startover my apps, its error and provide me this message :
\main.go:23:2: undefined: conn
How can I resolve this?
Anyhelp will appreciate
First, if you want to access something from another package, it has to be exported. In Go, if you want to export something you name it with first letter as uppercase (in your case, it should be Conn
instead of conn
).
Second, when you use defer
it will get executed when the function returns. In your case, it returns immediately, so the connection is closed immediately.
Solution:
var Conn *sql.DB
func InitFirebird() {
var (
dbDriver = beego.AppConfig.String("DB_CONNECTION")
dbUsername = beego.AppConfig.String("DB_USERNAME")
dbPassword = beego.AppConfig.String("DB_PASSWORD")
dbServer = beego.AppConfig.String("DB_HOST")
// dbPort = beego.AppConfig.String("DB_PORT")
dbFileName = beego.AppConfig.String("DB_DATABASE")
)
Conn, _ = sql.Open(dbDriver, dbUsername+":"+dbPassword+"@"+dbServer+"/"+dbFileName)
}
Now in your main package:
func init() {
utils.InitFirebird()
}
func main() {
if beego.BConfig.RunMode == "dev" {
beego.BConfig.WebConfig.DirectoryIndex = true
beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
}
var n int
defer utils.Conn.Close() // <-- Close here
utils.Conn.QueryRow("SELECT Count(*) FROM rdb$relations").Scan(&n)
fmt.Println("Relations count=", n)
beego.Run()
}
Here Close()
won't get executed immediately because beego.Run()
will block.
PS: Passing DB connection using global variable is not recommended. If you want to learn more check this out: https://www.alexedwards.net/blog/organising-database-access