I have a simple DbSession middleware setting a *db.SQL value to a context key of 'db'. I add an instance of that middleware to my router, yet when handling requests, the 'db' key does not exist in the context's keys.
I've added logging to the middleware and can verify that it is never being invoked, despite being added to the router with Use(). I also checked the context Keys and didn't see my 'db' key there.
This is my middleware.
// DbSession returns a gin middleware adding the database connection to the request context.
func DbSession(db *sql.DB) gin.HandlerFunc {
return func(c *gin.Context) {
fmt.Println("inside DbSession middleware")
c.Set("db", db)
c.Next()
}
}
And this is how it gets added in my main() function.
var db *sql.DB
func main() {
initEnv()
initDb()
defer db.Close()
r := InitRouter()
r.Use(DbSession(db))
_ = r.Run()
}
In my handler, I try to retrieve it.
func GetProfile(c *gin.Context) {
// ...
// Get our db session from the request context.
db := c.MustGet("db").(*sql.DB)
// ...
}
When the endpoint is accessed, I expect the context to have the 'db' key and its associated *sql.DB value. Instead I get the following panic.
[GIN-debug] Listening and serving HTTP on :8080
2019/07/13 11:45:05 http: panic serving [::1]:55014: Key "db" does not exist
This seems like such a trivial example, and I expected it to "Just Work (tm)". I figure it must be something really trivial that I've overlooked. Any and all insight is greatly appreciated.