From 024caeea2547ff50f8ec1c4e5dda2b712f0fb2f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 4 Oct 2022 03:15:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E8=AF=B7=E6=B1=82=E7=BB=93?= =?UTF-8?q?=E6=9E=9C=E6=94=AF=E6=8C=81gzip=E8=A7=A3=E5=8E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rpc.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/rpc.go b/rpc.go index fcebc6f..2dcce9c 100644 --- a/rpc.go +++ b/rpc.go @@ -9,6 +9,7 @@ package rpc import ( "bytes" + "compress/gzip" "encoding/json" "errors" "fmt" @@ -334,6 +335,7 @@ func (r *request) Send(ctx *gin.Context, serviceFlag string, apiFlag string, par if !r.httpCodeIsSuccess(response.StatusCode, successHttpCodeList) { return fmt.Errorf("HTTP状态码异常 : %v -> %v", response.StatusCode, response.Status) } + // 解析响应的业务数据 code, message, data = r.getCodeAndMessageAndData(responseBody, responseFieldCfg) if !r.codeIsSuccess(code, successBusinessCodeList) { @@ -350,6 +352,37 @@ func (r *request) Send(ctx *gin.Context, serviceFlag string, apiFlag string, par return err } +// getResponseBody 获取响应体 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 3:10 2022/10/4 +func (r *request) getResponseBody(response *httpclient.Response) ([]byte, error) { + var ( + responseBody []byte + err error + gzipInstance *gzip.Reader + buf bytes.Buffer + ) + if responseBody, err = io.ReadAll(response.Body); nil != err { + return nil, err + } + // 判断返回值是否经过gzip压缩 + responseGzip := response.Header.Get("content-encoding") + if strings.ToLower(responseGzip) == "gzip" { + // 压缩过的数据,在处理response body + if gzipInstance, err =gzip.NewReader(bytes.NewReader(responseBody)); nil != err { + return nil, err + } + defer gzipInstance.Close() + if _, err = io.Copy(&buf, gzipInstance); nil != err { + return nil, err + } + return buf.Bytes(), nil + } + return responseBody, nil +} + // GetHttpClient 获取client实例 // // Author : go_developer@163.com<白茶清欢>