I am currently trying to work on a small Go project, and I have a problem I am trying to solve.
I'm currently using github.com/jinzhu/gorm
to handle database operations for the backend of a GraphQL server, and I wanted to be able to store the DB connection in a global variable accessible throughout the entire project (including sub-packages).
My first attempt was at creating a variable named db
by doing the following in my main.go
file:
var db *gorm.DB
var err error
then inside the init()
function:
func init() {
db, err = gorm.Open("postgres", "credential stuff here")
db.AutoMigrate(&modelStructHere)
defer db.Close()
}
There isn't any crashing, but I would assume due to scoping, the db
variable is only usable inside main.go
, but I also need to be able to use this inside gql/gql.go
, where my GraphQL resolver is currently located.
Perhaps I should move this chunk of code (DB init) to the actual resolver file, since there's really no use for DB operations outside of such a thing anyway, so maybe that's the problem?
Thanks in advance!