duancanjiu3754 2015-07-27 12:40
浏览 44
已采纳

从AppEngine的上下文中获取* http.Request

I'm using app engine, and creating context.Context (golang.org/x/net/context) variable from the *http.Request.

    c := appengine.NewContext(r)

I'm passing the context around and I'm trying to figure out a way to get the *http.Request from the context.Context in order to log the http.Request.

I search all over the doc but I couldn't find any solution.

  • 写回答

1条回答 默认 最新

  • douyue7408 2015-07-27 13:15
    关注

    appengine.NewContext(r) returns a value of type appengine.Context. This is not the same as the Context type of the golang.org/x/net/context package!

    Having a value of type appengine.Context, you can't get the *http.Request you used to create it. If you will need the *http.Request, you have to take care of passing that around yourself (you have it, since you use that to create the context).

    Note that appengine.Context (which is an interface type) has a method Context.Request(), but that is for internal use only, it is not exported for anyone to call it. And also it returns an interface{} and not a *http.Request. Even if it returns a value holding a *http.Request, you can't rely on it as this method may be changed or removed in future versions.

    Passing the *http.Request along with the appengine.Context is the best way. Trying to get it from the context is just "wizardry" and might break with a new SDK release. If you want to simplify it, you may create a wrapper struct and pass that wrapper instead of 2 values, for example:

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

    And a helper func:

    func CreateCtx(r *http.Request) Wrapper {
        return Wrapper{appengine.NewContext(r), r}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?