dqd72925 2018-10-18 16:42
浏览 1730

在Golang中使ioutil.ReadAll(response.Body)引发错误

For some reason, I cannot seem to get ioutil.ReadAll(res.Body), where res is the *http.Response returned by res, err := hc.Do(redirectRequest) (for hc http.Client, redirectRequest *http.Request).

Testing strategy thus far

Any time I see hc.Do or http.Request in the SUT, my instinct is to spin up a fake server and point the appropriate application states to it. Such a server, for this test, looks like this :

badServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 
    // some stuff
    w.Write([some bad bytes])
}))
defer badServer.Close()

I don't seem to have a way to control res.Body, which is literally the only thing keeping me from 100% test completion against the func this is all in.

I tried, in the errorThrowingServer's handler func, setting r.Body to a stub io.ReadCloser that throws an error when Read() is called, but that doesn't effect res.

  • 写回答

2条回答 默认 最新

  • duanshan2988 2018-10-18 16:57
    关注

    As far as I could find perusing the source files for all of the working parts, the only way to get http.Response.Body.Read() to fail is commented here:

    https://golang.org/src/net/http/response.go#L53

    The response body is streamed on demand as the Body field is read. If the network connection fails or the server terminates the response, Body.Read calls return an error.

    Or there is the possibility in ioutil.ReadAll() for it to return bytes.ErrTooLarge here:

    https://golang.org/src/io/ioutil/ioutil.go#L20

    If the buffer overflows, we will get bytes.ErrTooLarge. Return that as an error. Any other panic remains.

    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧