猿问

Fiddler 环绕 JSON 响应

我有一个在 Go 中实现的 Web 服务,它从外部服务返回一个 JSON 结构。返回对象后,它看起来像这样:

{"otherServiceInfoList":[],"action...

我的 Go Web 服务只是将 JSON 读取到一个切片中:

response, err := ioutil.ReadAll(resp.Body)

并将其返回给客户端:

w.Write(response)

响应在 Postman 中按原样显示,但 Fiddler 预先和附加响应如下:

34ee
{"otherServiceInfoList":[],"...
0

注意前导34ee和尾随0.

然后我被提升来转换响应:

“响应已编码,可能需要在检查前进行解码。”

接受提示 removes 返回原始 JSON。Go 的w.write方法是应用了额外的字符,还是特定于 Fiddler?

顺便说一句,我在写入缓冲区之前设置了以下标头:

w.Header().Set("Content-Type", "application/json; charset=UTF-8")


DIEA
浏览 161回答 2
2回答

慕容森

这是 http 1.1 分块响应。该协议将发送格式:size-of-chunk-in-hexchunk...最终块大小为 0 表示响应结束。您的示例显示响应为 13550 字节,并以一个块发送。

眼眸繁星

您正在处理分块响应。我不确定您的最终目标是什么,但有几种不同的选择。消息来源本身说;    // Body represents the response body.    //    // 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 Body is automatically dechunked if the server replied    // with a "chunked" Transfer-Encoding.    Body io.ReadCloser所以例如这里; response, err := ioutil.ReadAll(resp.Body)在您中继来自其他服务的响应的地方,您可以通过使提供的服务resp设置一个 Transfer-Encoding 标头并使用分块值来解决问题,假设您也可以访问该 api。如果您只在这个中间层工作,那么您必须在编写响应之前自己拆分响应。如果您在 Fiddler 中监控的请求没有chunkedTransfer-Encoding,只需添加它可能会导致 Fiddler 将其显示为与您在 Postman 中看到的相同。
随时随地看视频慕课网APP

相关分类

Go
我要回答