google-app-engine - 从 AppEngine 上的上下文获取 *http.Request

标签 google-app-engine http go

我正在使用应用引擎,并从 *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.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}
}

关于google-app-engine - 从 AppEngine 上的上下文获取 *http.Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31653361/

相关文章:

go - 如何在 go 模型中包装 proto 消息

java - 在 AppEngine 中安排任务

c++ - 在 C++ 中通过 HTTP POST 上传文件

http - if-match HTTP header 是否需要两阶段提交?

go - 在 go (1.18) 中对泛型进行多态实现的最佳方法是什么?

go - 使用 go get 命令获取 "mkdir home/user permission denied"

python - google app engine python 日志级降噪

google-app-engine - 谷歌应用引擎上的 Grails

google-app-engine - 当我禁用数据存储写入时,如何启动 Mapreduce 作业?

javascript - 一个特定的 post 调用被调用两次?