在AppEngine上从Context获取* http.Request

时间:2015-07-27 12:40:27

标签: google-app-engine http go

我正在使用app引擎,并从context.Context创建*http.Request(golang.org/x/net/context)变量。

    c := appengine.NewContext(r)

我正在传递上下文,并且我试图找到一种方法从*http.Request获取context.Context以便记录http.Request

我搜索了整个文档,但我找不到任何解决方案。

1 个答案:

答案 0 :(得分:3)

appengine.NewContext(r)返回appengine.Context类型的值。这与Context包的golang.org/x/net/context类型不同!

拥有appengine.Context类型的值,您无法获得用于创建它的*http.Request。如果你需要*http.Request,你必须照顾自己周围的传递(你拥有它,因为你用它来创建上下文)。

请注意appengine.Context(这是一种接口类型)有一个方法Context.Request(),但这仅供内部使用,不会导出任何人调用它。它还会返回interface{}而不是*http.Request。即使它返回的值为*http.Request,也不能依赖它,因为在将来的版本中可能会更改或删除此方法。

*http.Requestappengine.Context 一起传递是的最佳方式。试图从上下文中获取它只是"巫术"并且可能会破坏新的SDK版本。如果要简化它,可以创建一个包装器结构并传递该包装而不是2个值,例如:

type Wrapper struct {
    C appengine.Context
    R *http.Request
}

辅助功能:

func CreateCtx(r *http.Request) Wrapper {
    return Wrapper{appengine.NewContext(r), r}
}