作为一个 Go 新手,我很难找出问题所在,但希望给你一些事实会有所帮助。
我正在使用一个 API,它以 gzip 格式返回其 Content-Encoding
。我写了以下代码来编码我的响应结构:
reader, err = gzip.NewReader(resp.Body)
defer reader.Close()
// print to standard out
//_, err = io.Copy(os.Stdout, reader)
//if err != nil {
// log.Fatal(err)
//}
// Decode the response into our tescoResponse struct
var response TescoResponse
err := json.NewDecoder(reader).Decode(&response)
为简洁起见,我删除了错误处理,但有趣的是,如果我取消注释打印到标准输出,我会得到预期的结果。但是,解码并没有给我我所期望的。任何指针?结构是否必须准确映射到响应??
这是完整的例子: https://play.golang.org/p/4eCuXxXm3T
最佳答案
DisableCompression, if true, prevents the Transport from requesting compression with an "Accept-Encoding: gzip" request header when the Request contains no existing Accept-Encoding value. If the Transport requests gzip on its own and gets a gzipped response, it's transparently decoded in the Response.Body. However, if the user explicitly requested gzip it is not automatically uncompressed.
建议的解决方案:
type gzreadCloser struct {
*gzip.Reader
io.Closer
}
func (gz gzreadCloser) Close() error {
return gz.Closer.Close()
}
//然后在你的 http 调用中....
if resp.Header.Get("Content-Encoding") == "gzip" {
resp.Header.Del("Content-Length")
zr, err := gzip.NewReader(resp.Body)
if err != nil {
return nil, err
}
resp.Body = gzreadCloser{zr, resp.Body}
}
// then you will be able to decode the json transparently
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
}
根据您的代码改编的解决方案:https://play.golang.org/p/Vt07y_xgak
关于json - 使用 Go 解码 gZip json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38982020/