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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献