This question already has an answer here:
- Reading gzipped HTTP response in Go 3 answers
- gzip compression to http responseWriter 3 answers
- Serving gzipped content for Go 2 answers
I am working on a Go-based JSON api which is processing files in mongodb and returning the output in JSON response.
This is how current GET api looks (Have added header into this api):
func (env *Env) GetHealthRecords(w http.ResponseWriter, r *http.Request) {
values := r.URL.Query()
healthPlan := values.Get(“health”)
healthRecords, error := env.DataFactories.HealthDataFactory.FindHealthRecords(healthPlan)
if error != nil {
http.Error(w, "An error occurred while processing your request", 500)
return
}
w.Header().Set("Accept-Encoding", "gzip") // <--Added This Header is existing code
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(&healthRecords)
}
Now have consumed the same API in another application: (Not able to figure it out how to un zip the data)
func (env *Env) ComsumeHealthRecords(health string) (logic.HealthRecords, error){
apiUrl := fmt.Sprintf(env.Url + "/health?plan=" + healthPlan)
var http = &http.Client{Timeout: 80 * time.Second, Transport: &http.Transport{ TLSClientConfig: &tls.Config{RootCAs: env.CA}}}
var healthRecords logic.HealthRecords
response, err := http.Get(apiUrl)
if err != nil {
return healthRecords, err
}
//reader, err = gzip.NewReader(response.Body) //<- How to use this line
defer response.Body.Close()
if err := json.NewDecoder(response.Body).Decode(&healthRecords); err != nil {
log.Printf("Error decoding benefits: %s", err.Error())
}
if(response.Status != "200 OK"){
err = errors.New(string(response.Status))
}
return healthRecords, err
}
</div>