我有一个在 Go 中实现的 Web 服务,它从外部服务返回一个 JSON 结构。返回对象后,它看起来像这样:
{"otherServiceInfoList":[],"action...
Run Code Online (Sandbox Code Playgroud)
我的 Go Web 服务只是将 JSON 读取到一个切片中:
response, err := ioutil.ReadAll(resp.Body)
Run Code Online (Sandbox Code Playgroud)
并将其返回给客户端:
w.Write(response)
Run Code Online (Sandbox Code Playgroud)
响应在 Postman 中按原样显示,但是 Fiddler 预先和附加响应如下:
34ee
{"otherServiceInfoList":[],"...
0
Run Code Online (Sandbox Code Playgroud)
注意前导34ee和尾随0.
然后我被提升来转换响应:
“响应已编码,可能需要在检查前进行解码。”
接受提示删除返回原始 JSON。Go 的w.write方法是应用了额外的字符,还是特定于 Fiddler?
顺便说一句,我在写入缓冲区之前设置了以下标头:
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
Run Code Online (Sandbox Code Playgroud)
您正在处理一个分块的响应。我不确定您的最终目标是什么,但有一些不同的选择。消息来源本身说;
// 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
Run Code Online (Sandbox Code Playgroud)
例如这里;response, err := ioutil.ReadAll(resp.Body)当您中继来自其他服务的响应时,您可以通过让提供的服务resp设置一个带有分块值的 Transfer-Encoding 标头来解决问题,假设您也有权访问该 api。如果您只在中间层工作,那么您必须在编写响应之前自行对响应进行分块。如果您在 Fiddler 中监视的请求没有chunkedTransfer-Encoding,则仅添加它可能会导致 Fiddler 显示它与您在 Postman 中看到的相同。