Golang/gin:如何将数据库传递给路由函数

huangapple go评论96阅读模式
英文:

Golang/gin: How to Pass db to router functions

问题

我正在使用gin框架。我在主函数中像这样打开sqlite数据库:

  1. func main() {
  2. ...
  3. db, err := sql.Open("sqlite3", "./libreread.db")
  4. CheckError(err)
  5. defer db.Close()
  6. ...
  7. }

我在主函数中有这些路由处理程序:

  1. ...
  2. r.GET("/", GetHomePage)
  3. r.GET("/signin", GetSignIn)
  4. r.POST("/signin", PostSignIn)
  5. ...

如何通过路由处理程序函数PostSignin(c *gin.Context)传递db值?

这样我就可以避免在每个函数中每次打开和关闭数据库。

更新:我正在使用go-sqlite3包。

谢谢!

英文:

I'm using gin framework. And I'm opening the sqlite database in the main function like this

  1. func main() {
  2. ...
  3. db, err := sql.Open("sqlite3", "./libreread.db")
  4. CheckError(err)
  5. defer db.Close()
  6. ...
  7. }

And I have these router handlers in the main function.

  1. ...
  2. r.GET("/", GetHomePage)
  3. r.GET("/signin", GetSignIn)
  4. r.POST("/signin", PostSignIn)
  5. ...

How to pass that db value through the router handler func PostSignin(c *gin.Context) ?

So that I could avoid opening and closing the database each time in the functions.

UPDATE: I'm using go-sqlite3 package.

Thanks!

答案1

得分: 2

假设你已经在db中初始化了你的SQL客户端,然后你可以将它传递给不同的路由:

  1. r.GET("/", GetHomePageHandler(&db))

在你的GetHomePageHandler函数中:

  1. func GetHomePageHandler(sqldb *SQLiteConn) func (*gin.Context) {
  2. return func (*gin.Context) {
  3. // ...
  4. }
  5. }

其中*SQLiteConn是你的SQL数据库实例的类型。我不知道你目前使用的是哪个包,所以这只是一个示例。

你还可以在这个答案中找到一种更优雅的解决方法。

英文:

Let's say you have your sql client initialized in db, then, you can pass it to different routes with

  1. r.GET("/", GetHomePageHandler(&db))

And in your GetHomePageHandler:

  1. func GetHomePageHandler(sqldb *SQLiteConn) func (*gin.Context) {
  2. return func (*gin.Context) {
  3. . . .
  4. }
  5. }

Where *SQLiteConn is the type of your sql db instance. I don't know which package you are currently using so this is just an example.

You can find also a more elegant way of solving it in this answer,

huangapple
  • 本文由 发表于 2017年6月4日 17:33:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/44352656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定