栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在读取响应正文时强加错误

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在读取响应正文时强加错误

查看的文档,

Response.Body
以了解何时从中读取可能返回错误:

// Body represents the response body.//// 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.//// The http Client and Transport guarantee that Body is always// non-nil, even on responses without a body or responses with// a zero-length body. It is the caller's responsibility to// close Body. The default HTTP client's Transport may not// reuse HTTP/1.x "keep-alive" TCP connections if the Body is// not read to completion and closed.//// The Body is automatically dechunked if the server replied// with a "chunked" Transfer-Encoding.Body io.ReadCloser

最简单的方法是从测试处理程序生成无效的HTTP响应。

怎么做?有很多方法,一种简单的方法是“撒谎”内容的长度:

handler := func(w http.ResponseWriter, r *http.Request) {    w.Header().Set("Content-Length", "1")}

该处理程序告诉它具有1个字节的正文,但实际上不发送任何内容。因此,在另一端(客户端)尝试从中读取1个字节时,显然不会成功,并且会导致以下错误:

Unable to read from body unexpected EOF

如果您需要模拟从请求正文(而不是从响应正文)读取错误



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415574.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号