将上下文传递给子目录

huangapple go评论70阅读模式
英文:

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))
}

huangapple
  • 本文由 发表于 2015年5月28日 00:18:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/30487979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定