Skip to content

Instantly share code, notes, and snippets.

@RobinUS2
Created November 17, 2015 09:18
Show Gist options
  • Save RobinUS2/ec875b5945f86943f152 to your computer and use it in GitHub Desktop.
Save RobinUS2/ec875b5945f86943f152 to your computer and use it in GitHub Desktop.
Read Go body bytes with GZIP support
package main
// License: Apache v2
import (
"bytes"
"compress/gzip"
"io/ioutil"
"net/http"
)
func readBodyBytes(r *http.Request) ([]byte, error) {
// Read body
bodyBytes, readErr := ioutil.ReadAll(r.Body)
if readErr != nil {
return nil, readErr
}
defer r.Body.Close()
// GZIP decode
if len(r.Header["Content-Encoding"]) > 0 && r.Header["Content-Encoding"][0] == "gzip" {
r, gzErr := gzip.NewReader(ioutil.NopCloser(bytes.NewBuffer(bodyBytes)))
if gzErr != nil {
return nil, gzErr
}
defer r.Close()
bb, err2 := ioutil.ReadAll(r)
if err2 != nil {
return nil, err2
}
return bb, nil
} else {
// Not compressed
return bodyBytes, nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment