json - 使用 Go 解码 gZip json

标签 json go gzip

作为一个 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

最佳答案

From the documenation :

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/

相关文章:

concurrency - 如何在没有死锁的情况下在缓冲 channel 上循环?

python - 用压缩数据填充 memcached,直接从 nginx 服务

c# - 在json中插入c#数组

json - Swift Alamofire JSON 解析

encoding - go.text 中的 iso-8859-1 编码支持

golang 强制对特定 ip 的 http 请求(类似于 curl --resolve)

java - 将 'Content-Encoding' 设置为 gzip 或 deflate 会导致 java.net.SocketException : Connection reset

python - 我如何在 Python 中解析 gzip 文件并在以后附加到它,即使它不存在?

mysql - 使用 MySQL 选择 JSON 字符串的特定值

javascript - 使用 Node js 动态构建 JSON