dream04110 2017-06-04 09:33
浏览 345

Golang / Gin:如何将db传递给路由器功能

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

func main() {
...
db, err := sql.Open("sqlite3", "./libreread.db")
CheckError(err)
defer db.Close()
...
}

And I have these router handlers in the main function.

...
r.GET("/", GetHomePage)
r.GET("/signin", GetSignIn)
r.POST("/signin", PostSignIn)
...

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条回答 默认 最新

  • douchongbang6011 2017-06-04 11:00
    关注

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

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

    And in your GetHomePageHandler:

    func GetHomePageHandler(sqldb *SQLiteConn) func (*gin.Context) {
        return  func (*gin.Context) {
          . . .
        }
    }
    

    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,

    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序