英文:
Passing context to sub-directory
问题
我有一个名为Context
的结构体,用于应用程序上下文。ConfigureRouter
函数接收上下文作为参数,并设置全局变量c
,以便同一文件中的中间件可以使用它。
var c *core.Context
func ConfigureRouter(ctx *core.Context, router *httprouter.Router) {
c = ctx //使上下文在所有中间件中可用
router.POST("/v1/tokens/create", token.Create) //使用httprouter
}
上面列出的一个路由调用了token.Create
(来自子目录的token
包),但它也需要上下文。
//token/token.go
func Create(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
//帮帮我!我需要上下文来做一些事情
}
我该如何将上下文传递给token
包?
英文:
I have a Context
struct that is used for the Application Context. The ConfigureRouter
function receives the context as a parameter and sets the global variable c
so middleware in the same file can use it.
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
}
The one route listed above calls token.Create
( from the token package which is a sub-directory) but it needs the context too.
//token/token.go
func Create(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
//Help! I need the context to do things
}
How can I pass the context to the token package?
答案1
得分: 1
你可以将Create函数重新定义为返回处理程序函数的函数:
func Create(ctx *core.Context) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
// 现在你有了上下文可以进行操作
}
}
其中httprouter.Handle
是由httprouter定义的函数类型,其定义为type Handle func(http.ResponseWriter, *http.Request, Params)
。
然后在ConfigureRouter
函数中可以这样使用:
func ConfigureRouter(ctx *core.Context, router *httprouter.Router) {
router.POST("/v1/tokens/create", token.Create(ctx))
}
英文:
You can redefine your Create function as a function that returns the handler function:
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
}
}
Where httprouter.Handle
is a func type defined by httprouter to be type Handle func(http.ResponseWriter, *http.Request, Params)
.
And then you would use it like this in ConfigureRouter
:
func ConfigureRouter(ctx *core.Context, router *httprouter.Router) {
router.POST("/v1/tokens/create", token.Create(ctx))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论