2016-01-24 85 views
2

在GAE Go中,为了记录,我们需要使用appengine.NewContext(r)创建一个新的上下文,它返回context.ContextGoogle App Engine context.Context vs gorilla context

如何使用此上下文在请求范围设置/获取变量?在Gorilla中,Context在上下文中有一个干净的Set/Get函数,这是我想在我的代码中使用的。但是我不想导入2个不同的上下文包。

GAE日志迫使您使用context.Context

//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? 
} 
+0

创建自定义处理程序类型(将上下文作为参数之一),并让您的路由器或某些中间件(首先在链中)调用NewContext来初始化它。 – elithrar

回答

0
import (
    "golang.org/x/net/context" 
    gorillacontext "github.com/gorilla/context"  
) 

我知道这是不是你想要的答案,但有没有办法解决它,因为在围棋标准库(由App Engine的使用)“context”包不提供与Gorilla的'context'包相比,您想要的功能。如果你想使用额外的框架来定义他们自己的“上下文”包,你将需要使用多个导入。

关于groups discussion上的这两个上下文有一个很好的观点,那就是Gorilla的上下文可能会被错误地命名,因为它们都用于不同的目的 - “App Engine存储凭证来发出RPC请求;大猩猩只是一个请求全局变量的容器“。