Reputation: 2204
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!
Upvotes: 2
Views: 2149
Reputation: 3985
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,
Upvotes: 3