【发布时间】:2016-03-06 21:33:17
【问题描述】:
我正在使用 Gin,https://gin-gonic.github.io/gin/,用 Golang 构建一个简单的 RESTful JSON API。
路线是这样设置的:
func testRouteHandler(c *gin.Context) {
// do smth
}
func main() {
router := gin.Default()
router.GET("/test", testRouteHandler)
router.Run(":8080")
}
我的问题是如何将参数传递给 testRouteHandler 函数?例如,一个公共数据库连接可能是一个希望在路由之间重用的东西。
将它放在全局变量中是最好的方法吗?或者 Go 中有什么方法可以将额外的变量传递给 testRouteHandler 函数? Go 中的函数是否有可选参数?
PS。我刚刚开始学习围棋,所以可能很明显我错过了一些东西:)
【问题讨论】:
-
我认为您正在寻找 HTTP 中间件这是一个很好的起点nicolasmerouze.com/middlewares-golang-best-practices-examples
-
正如@MIkCode 所说,中间件是必经之路……看看 Gin 的自定义中间件。 github.com/gin-gonic/gin#custom-middleware
-
中间件示例here(下面有几篇文章)