douyu0725 2018-07-13 19:56
浏览 52
已采纳

全局变量和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!

  • 写回答

1条回答 默认 最新

  • douzhan8303 2018-07-13 20:33
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统