Golang: Gzip uncompressed http.Response.Body

I am creating a Go app that takes an http.Response object and stores it (response headers + body) in a redis hash. When the app receives http.Response.Body

that is not gzip related, I want to gzip it before storing it in the cache.

My confusion stems from my inability to clearly understand the Go interfaces io

and how to negotiate between http.Response.Body

io.ReadCloser

and gzip Writer

. I'm guessing there is an elegant, streaming solution here, but I can't seem to get it to work.

Any help would be greatly appreciated!

+3


source to share


1 answer


If you have already determined that the body is uncompressed, and if you need []byte

compressed data (instead of, for example, already having io.Writer

one that you could write to, for example, if you want to save the body to a file that you want to transfer to a file not to a buffer) then something like this should work:

func getCompressedBody(r *http.Response) ([]byte, error) {
    var buf bytes.Buffer
    gz := gzip.NewWriter(&buf)
    if _, err := io.Copy(gz, r.Body); err != nil {
        return nil, err
    }
    err := gz.Close()
    return buf.Bytes(), err
}

      



(this is just an example and will most likely be in a string instead of a function, if you want it like a fuction then it should probably *http.Response

be used instead io.Reader

).

+6


source







All Articles