我正在使用应用引擎,并从 *http.Request
创建 context.Context
(golang.org/x/net/context) 变量。
c := appengine.NewContext(r)
我正在传递上下文,我正在尝试找出一种方法来从 context.Context
中获取 *http.Request
以便记录http.Request
。
我搜索了整个文档,但找不到任何解决方案。
最佳答案
appengine.NewContext(r)
返回 appengine.Context
类型的值.这与 Context
不同golang.org/x/net/context
的类型包!
具有 appengine.Context
类型的值,您无法获取用于创建它的 *http.Request
。如果您需要 *http.Request
,则必须注意将其传递给自己(您拥有它,因为您使用它来创建上下文)。
请注意,appengine.Context
(它是一个接口(interface)类型)有一个方法 Context.Request()
,但它仅供内部使用,不会导出任何人都可以调用它。它还返回一个接口(interface){}
,而不是一个*http.Request
。即使它返回一个包含 *http.Request
的值,您也不能依赖它,因为此方法可能会在未来版本中更改或删除。
将 *http.Request
与 appengine.Context
一起传递是最好的方法。试图从上下文中获取它只是“巫术”,并且可能会随着新的 SDK 版本而中断。如果你想简化它,你可以创建一个包装器结构并传递该包装器而不是 2 个值,例如:
type Wrapper struct {
C appengine.Context
R *http.Request
}
还有一个辅助函数:
func CreateCtx(r *http.Request) Wrapper {
return Wrapper{appengine.NewContext(r), r}
}
关于google-app-engine - 从 AppEngine 上的上下文获取 *http.Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31653361/