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 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)