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

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

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

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

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

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

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

  reader,err = gzip.NewReader(response.Body)
  code>  pre> 
 
 

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

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
}

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.