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

如何从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条)

报告相同问题?

悬赏问题

  • ¥25 C语言代码,大家帮帮我
  • ¥15 请问以下文字内容及对应编码是用了什么加密算法或压缩算法呢?
  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)
  • ¥15 无法使用此凭据登录,因为你的域不可用,如何解决?(标签-Windows)
  • ¥15 yolov9的训练时间
  • ¥15 二叉树遍历没有报错但无法正常运行
  • ¥15 在linux系统下vscode运行robocup3d上场球员报错
  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿