doushi1957 2018-10-12 05:51
浏览 567
已采纳

如何从Golang的http响应中读取压缩数据

I have a http response which is gzipped.

resp, err := client.Do(req)
    if err != nil {
        return "", err
    }

    defer resp.Body.Close()

    if resp.StatusCode == http.StatusOK {
        var buf bytes.Buffer


    }

How can I ungzipped it and parse it into my struct?

I saw a question like this: Reading gzipped HTTP response in Go

but it output the response into a standard output. Also the example runs into error, the

reader, err = gzip.NewReader(response.Body)

returns err as "EOF". How can I debug this?

  • 写回答

2条回答 默认 最新

  • dongya2030 2018-10-12 06:28
    关注

    I solved this by reading this code: https://gist.github.com/xyproto/f4915d7e208771f3adc4

    here is the code which helped me.

    // Write gunzipped data to a Writer
    func gunzipWrite(w io.Writer, data []byte) error {
        // Write gzipped data to the client
        gr, err := gzip.NewReader(bytes.NewBuffer(data))
        defer gr.Close()
        data, err = ioutil.ReadAll(gr)
        if err != nil {
            return err
        }
        w.Write(data)
        return nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵
  • ¥15 cfx离心泵非稳态计算