英文:
Google App Engine context.Context vs gorilla context
问题
在GAE Go中,为了记录日志,我们需要使用appengine.NewContext(r)
创建一个新的上下文,它返回context.Context
。
我该如何使用这个上下文在请求范围内设置/获取变量?在Gorilla中,Context在上下文中有干净的Set/Get函数,这正是我想在我的代码中使用的。然而,我不想导入两个不同的上下文包。
GAE日志强制使用context.Context
。
<!-- language : go -->
//handlerFunc
func MyFunc(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
// 我想在上下文中设置请求范围的变量,并将其传递给doSomething。
doSomething(ctx,w,r);
}
func doSomething(ctx context.Context, w http.ResponseWriter, r *http.Request) {
log.Debugf(ctx, "开始doSomething"); //需要上下文参数
// 如何从上下文中获取请求范围的变量?使用Gorilla Context吗?
}
英文:
In GAE Go, in order to log, we need to create a new context using appengine.NewContext(r)
which returns context.Context
.
How do I use this context to set/get variables at request scope? In Gorilla, Context has a clean Set/Get functions on context which is what I want to use in my code. However I do not want to import 2 different context packages.
GAE logging forces you to use context.Context
.
<!-- language : go -->
//handlerFunc
func MyFunc(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
// I want to set request scoped variables in context and pass it to doSomething.
doSomething(ctx,w,r);
}
func doSomething(ctx context.Context, w http.ResponseWriter, r *http.Request) {
log.Debugf(ctx, "Beginning doSomething"); //requires context parameter
// get the request scoped variables from context. How? Use Gorilla Context?
}
答案1
得分: 0
import (
"golang.org/x/net/context"
gorillacontext "github.com/gorilla/context"
)
我知道这不是你想要的答案,但是由于Go标准库中的'context'包(被App Engine使用)与Gorilla的'context'包相比,没有提供你想要的功能,所以无法避免。如果你想要使用定义了自己'context'包的其他框架,你需要使用多个导入。
在一个讨论组中提到了这两个上下文的一个很好的观点,可能Gorilla的上下文命名不准确,因为它们用于不同的目的 - "App Engine的上下文存储用于进行RPC请求的凭据;而Gorilla的上下文只是一个请求全局变量的容器。"
英文:
import (
"golang.org/x/net/context"
gorillacontext "github.com/gorilla/context"
)
I know this isn't the answer you want, but there's no way around it since the 'context' package in the Go standard library (used by App Engine) doesn't provide the functionality you want as compared to Gorilla's 'context' package. If you want to use additional frameworks that define their own 'context' packages, you will need to use multiple imports.
There's a good point made about these two contexts on a groups discussion in that possibly Gorilla's context is misnamed since they are both used for different purposes - "The App Engine one stores credentials to make RPC requests; the Gorilla one is just a container for request globals."
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论