donglao4370 2015-11-04 21:29
浏览 500
已采纳

在Go中,如何重用ReadCloser?

I have a http request which I need to inspect the body of. But when I do, the request fails. I'm assuming this had to do with the Reader needing to be reset, but googling along the lines of go ioutil reset ReadCloser hasn't turned anything up that looks promising.

c is a *middleware.Context, c.Req.Request is a http.Request, and c.Req.Request.Body is an io.ReadCloser

contents, _ := ioutil.ReadAll(c.Req.Request.Body)
log.Info("Request: %s", string(contents))
proxy.ServeHTTP(c.RW(), c.Req.Request)

Specifically the error I get is http: proxy error: http: ContentLength=133 with Body length 0

  • 写回答

1条回答 默认 最新

  • duanbushi1479 2015-11-04 21:34
    关注

    You can't reset it, because you've already read from it and there's nothing left in the stream.

    What you can do is take the buffered bytes you already have, and replace the Body with a new io.ReadCloser

    contents, _ := ioutil.ReadAll(c.Req.Request.Body)
    log.Info("Request: %s", string(contents))
    c.Req.Request.Body = ioutil.NopCloser(bytes.NewReader(contents))
    proxy.ServeHTTP(c.RW(), c.Req.Request)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?