golang http client.Do(req)无法二次使用

2018-08-10  本文已影响0人  咣咣当

初始化client,以及request竟然无法调用第二次,奇了八怪。

没怎么深入阅读源码,但是知道问题出在哪了。

首先代码长这样:

resp, err := client.Do(req)
resp, err := client.Do(req)

本来想着过一段时间刷新一下数据,来看看数据有什么变化,所以就想着能复用req,但是没想到报错:

: http: ContentLength=15 with Body length 0

这是为什么呢。深入调查了一下,先看下req长啥样

req, err = http.NewRequest("POST", "some url", strings.NewReader("articleId="+articleId))

其中第三个参数就是body,
req.Body长这样:

type Reader struct {
    s        string
    i        int64 // current reading index
    prevRune int   // index of previous rune; or < 0
}

看到这就突然明白了,client.Do方法在读取body数据时会根据Reader中的i值进行读取,即调用其Read方法,i值都会改变,当然读取完,i值也就变成contentLength。那么下次再进行使用的时候,因为读取不出任何数据,导致如上错误 Body length 0

这种情况应该怎么解决呢。

。。。

new一个新的Reader...

上一篇 下一篇

猜你喜欢

热点阅读