[Golang] Export go-pg by variable
Dec 10, 2020
What I learned today
How to export Database variable to other packages using go-pg
Before:
// package pgdbfunc DB() (Con *pg.DB) {Con = pg.Connect(options)if Con == nil {fmt.Printf(“Problem Occurred”)} else {fmt.Printf(“DB connected”)}return}// call from other packages_, err := pgdb.DB().Query(...)
This way had one drawback: Calling database by function is tiresome, because I have to type parenthesis.
Now:
// package pgdbvar Con *pg.DBfunc init() {// here are the same as before.}// call from other packages_, err := pgdb.Con.Query(..)