Franva
Franva

Reputation: 7077

How to read gzipped data from http response in Golang

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?

Upvotes: 0

Views: 3889

Answers (2)

novalagung
novalagung

Reputation: 11502

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.

Upvotes: 2

Franva
Franva

Reputation: 7077

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
}

Upvotes: 0

Related Questions