douyingtai6662 2019-09-20 12:27
浏览 128

如何在HTTP API中gzip和un-gzip JSON响应[重复]

This question already has an answer here:

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>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 phython路径名过长报错 不知道什么问题
    • ¥15 深度学习中模型转换该怎么实现
    • ¥15 HLs设计手写数字识别程序编译通不过
    • ¥15 Stata外部命令安装问题求帮助!
    • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
    • ¥15 TYPCE母转母,插入认方向
    • ¥15 如何用python向钉钉机器人发送可以放大的图片?
    • ¥15 matlab(相关搜索:紧聚焦)
    • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
    • ¥15 Arduino无法同时连接多个hx711模块,如何解决?