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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测