Search code examples
gographqlgraphql-go

Global variables and Go


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!


Solution

  • Alex's comment is spot on. Create a folder named "database" and inside put a file called "database.go" containing this:

    package database
    // the imports go here
    var DB *gorm.DB
    

    Now you can use it wherever you like with database.DB. You should not make the error variable global, handle it in the same function that initializes the DB. The init function can be in any place, usually you want it at the beginning of your program in the main function.