// Package rpc ... // // Description : rpc ... // // Author : go_developer@163.com<白茶清欢> // // Date : 2023-02-14 14:33 package rpc import ( "bytes" "compress/gzip" "encoding/json" "fmt" "io" "net/http" "strings" "git.zhangdeman.cn/zhangdeman/util" "github.com/ddliu/go-httpclient" ) var ( // HttpClient http 客户端 HttpClient *httpClient ) func init() { HttpClient = &httpClient{} } type httpClient struct { } // Send 统一发送请求方法 // // Author : go_developer@163.com<白茶清欢> // // Date : 14:37 2023/2/14 func (hc *httpClient) Send(requestURL string, method string, header map[string]string, param map[string]interface{}, options httpclient.Map, receiver interface{}) ([]byte, error) { var ( err error response *httpclient.Response c *httpclient.HttpClient responseData []byte ) if nil == param { param = make(map[string]interface{}) } if nil == header { header = make(map[string]string) } if nil == options { options = map[interface{}]interface{}{} } c = httpclient.NewHttpClient() c.Headers = header c.WithOptions(options) byteData, _ := json.Marshal(param) if response, err = c.Do(method, requestURL, header, bytes.NewReader(byteData)); nil != err { return nil, err } if response.StatusCode != http.StatusOK { return nil, fmt.Errorf("%v : %v", response.StatusCode, response.Status) } if responseData, err = hc.getResponseBody(response); nil != err { return nil, err } if nil == receiver { return responseData, nil } if err = json.Unmarshal(responseData, receiver); nil != err { return responseData, err } return responseData, err } // getResponseBody ... // // Author : go_developer@163.com<白茶清欢> // // Date : 15:12 2023/2/14 func (hc *httpClient) 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 func() { _ = gzipInstance.Close() }() if _, err = io.Copy(&buf, gzipInstance); nil != err { return nil, err } responseBody = buf.Bytes() } // 判断是否为gbk编码,若是,转为utf8 isGBK := strings.Contains(strings.ToLower(response.Header.Get("content-type")), "gbk") if isGBK { return []byte(util.String.Convert(string(responseBody), "gbk", "utf-8")), nil } // 判断是否为gb2312,若是,转为utf8 isGB2312 := strings.Contains(strings.ToLower(response.Header.Get("content-type")), "gb2312") if isGB2312 { return []byte(util.String.Convert(string(responseBody), "gb2312", "utf-8")), nil } return responseBody, nil }