我有一个用于应用程序上下文的Context结构。ConfigureRouter函数接收上下文作为参数,并设置全局变量c,以便同一文件中的中间件可以使用它。
var c *core.Context
func ConfigureRouter(ctx *core.Context, router *httprouter.Router) {
c = ctx //make context available in all middleware
router.POST("/v1/tokens/create", token.Create) //using httprouter
}上面列出的一条路由调用token.Create (来自作为子目录的令牌包),但它也需要上下文。
//token/token.go
func Create(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
//Help! I need the context to do things
}如何将上下文传递给令牌包?
发布于 2015-05-27 16:28:54
可以将Create函数重新定义为返回处理程序函数的函数:
func Create(ctx *core.Context) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
// Now you have the context to do things
}
}其中,httprouter.Handle是httprouter定义为type Handle func(http.ResponseWriter, *http.Request, Params)的func类型。
然后在ConfigureRouter中像这样使用它
func ConfigureRouter(ctx *core.Context, router *httprouter.Router) {
router.POST("/v1/tokens/create", token.Create(ctx))
}https://stackoverflow.com/questions/30487979
复制相似问题