package client import ( "errors" "fmt" "net/http" "github.com/zeromicro/go-zero/core/logx" "chengdu-lenntc/third-platform-sdk/util" ) // HttpRequest http请求参数 type HttpRequest struct { Headers map[string]string // 请求header参数 QueryArgs map[string]any // 请求query参数 BodyArgs map[string]any // 请求body参数 } // HttpResponse http响应结果 type HttpResponse struct { Result any // 响应的body数据结构, 必须为指针类型 RespHeader *http.Header // 响应header } // ThirdClient 第三方平台的client type ThirdClient interface { // HttpGet GET请求 HttpGet(url string, req *HttpRequest, resp *HttpResponse) error // HttpPost POST请求 HttpPost(url string, req *HttpRequest, resp *HttpResponse) error // HttpPut PUT请求 HttpPut(url string, req *HttpRequest, resp *HttpResponse) error // HttpDelete DELETE请求 HttpDelete(url string, req *HttpRequest, resp *HttpResponse) error // DoHttp 发起http请求 DoHttp(method string, url string, req *HttpRequest, resp *HttpResponse) error } type ThirdClientImpl struct { log logx.Logger } func NewThirdClient(log logx.Logger) *ThirdClientImpl { return &ThirdClientImpl{ log: log, } } func (c *ThirdClientImpl) HttpGet(url string, req *HttpRequest, resp *HttpResponse) error { return c.DoHttp(http.MethodGet, url, req, resp) } func (c *ThirdClientImpl) HttpPost(url string, req *HttpRequest, resp *HttpResponse) error { return c.DoHttp(http.MethodPost, url, req, resp) } func (c *ThirdClientImpl) HttpPut(url string, req *HttpRequest, resp *HttpResponse) error { return c.DoHttp(http.MethodPut, url, req, resp) } func (c *ThirdClientImpl) HttpDelete(url string, req *HttpRequest, resp *HttpResponse) error { return c.DoHttp(http.MethodDelete, url, req, resp) } func (c *ThirdClientImpl) DoHttp(method string, url string, req *HttpRequest, resp *HttpResponse) error { // 发起请求 reqConfig := &util.ReqConfig{ Headers: req.Headers, QueryArgs: req.QueryArgs, BodyArgs: req.BodyArgs, } hc := util.NewHttpClient(c.log).NewRequest(method, url, reqConfig).Do() if hc.Error != nil { return hc.Error } var responseHeader *http.Header if hc.Response != nil { responseHeader = &hc.Response.Header } // 检查http响应错误 if err := c.checkResponseError(hc.Response); err != nil { c.log.WithFields([]logx.LogField{{Key: "method", Value: method}, {Key: "url", Value: url}, {Key: "reqConfig", Value: reqConfig}}...). Errorf("[ThirdClientImpl][DoHttp] checkResponseError err:%s", err) return err } // 获取响应结果 if resp == nil { return nil } result := resp.Result if err := hc.Result(result).Error; err != nil { return err } resp.Result = result resp.RespHeader = responseHeader return nil } // 检查http响应错误 func (c *ThirdClientImpl) checkResponseError(r *util.Response) error { if r.StatusCode >= 200 && r.StatusCode < 300 { return nil } return errors.New(fmt.Sprintf("http response error, status code: %d, status: %s", r.StatusCode, r.Status)) }