douke1942 2019-07-13 17:10
浏览 334

尽管gin路由器使用了gin中间件,但似乎仍未调用的问题

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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
    • ¥15 fluent的在模拟压强时使用希望得到一些建议
    • ¥15 STM32驱动继电器
    • ¥15 Windows server update services
    • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
    • ¥15 模糊pid与pid仿真结果几乎一样
    • ¥15 java的GUI的运用
    • ¥15 Web.config连不上数据库
    • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
    • ¥15 怎么配置广告联盟瀑布流