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

如何从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?

图片转代码服务由CSDN问答提供 功能建议

我收到一个已压缩的http响应。

  resp  ,err:= client.Do(req)
如果err!= nil {
 return“”,err 
} 
 
如果resp.StatusCode ==,则推迟resp.Body.Close()
 
  http.StatusOK {
 var buf bytes.Buffer 
 
 
} 
   
 
 

如何解压缩并将其解析为我的结构?

我看到了这样的问题: 阅读gzip压缩的HTTP Go中的响应

,但它将响应输出到标准输出中。 同样该示例也出错,

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

将err返回为“ EOF”。 我该如何调试?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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
    }
    
    打赏 评论
  • dtq26360 2018-10-12 06:27

    Golang by default will automatically decode the body of gzipped response. So practically you just need to read the response body and it's enough, no need to do anything afterwards.

    Below is an explanation from https://golang.org/pkg/net/http/#Transport:

    ... 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.

    So if you get EOF error, the problem might not be because the gzip encoding stuff, it could be because there is actually no data on the response body.

    Btw, to you can check whether response is gzipped or not is by checking the Content-Encoding response header.

    打赏 评论

相关推荐 更多相似问题