httpclient/resty.go

102 lines
3.0 KiB
Go

// Package httpclient ...
//
// Description : httpclient ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-05-31 14:59
package httpclient
import (
"encoding/json"
"git.zhangdeman.cn/gateway/httpclient/define"
"git.zhangdeman.cn/zhangdeman/serialize"
"github.com/go-resty/resty/v2"
"github.com/tidwall/gjson"
"net/http"
"net/textproto"
"strings"
)
// NewRestyClient 获取resty client
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:00 2024/5/31
func NewRestyClient(reqConfig *define.Request) (*resty.Client, *resty.Request) {
client := resty.New()
request := client.R()
if nil == reqConfig {
return client, request
}
formatHeader(reqConfig)
client.SetAllowGetMethodPayload(true) // 配置 GET 请求允许带 Body
client.SetJSONMarshaler(json.Marshal) // 序列化方法
client.SetJSONEscapeHTML(true) // 处理html实体字符
client.SetJSONUnmarshaler(serialize.JSON.UnmarshalWithNumber) // 反序列化方法
request.SetPathParams(reqConfig.PathParam) // 设置path中的参数
request.SetQueryParams(reqConfig.Query) // 设置query参数
request.SetHeaders(reqConfig.Header) // 设置header
request.URL = reqConfig.FullUrl // 请求接口
for pathParamName, pathParamValue := range reqConfig.PathParam {
if len(pathParamValue) == 0 {
continue
}
reqConfig.FullUrl = strings.ReplaceAll(reqConfig.FullUrl, "{#"+pathParamName+"#}", pathParamValue)
}
request.Method = reqConfig.Method // 请求方法
cookieList := make([]*http.Cookie, 0)
for cookieName, cookieValue := range reqConfig.Cookie {
cookieList = append(cookieList, &http.Cookie{
Name: cookieName,
Value: cookieValue,
})
}
request.SetCookies(cookieList) // 设置cookie
setRestyBody(reqConfig, request) // 设置请求Body
return client, request
}
// setRestyBody 设置请求BODY
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 17:18 2024/5/31
func setRestyBody(reqConfig *define.Request, request *resty.Request) {
if nil == reqConfig.Body || len(reqConfig.Body) == 0 {
return
}
if strings.Contains(strings.ToLower(reqConfig.ContentType), "application/json") {
request.SetBody(reqConfig.Body)
return
}
if strings.Contains(strings.ToLower(reqConfig.ContentType), "application/x-www-form-urlencodeds") {
bodyStr := serialize.JSON.MarshalForString(reqConfig.Body)
bodyData := map[string]string{}
jsonObj := gjson.Parse(bodyStr)
jsonObj.ForEach(func(key, value gjson.Result) bool {
bodyData[key.String()] = value.String()
return true
})
request.SetFormData(bodyData)
}
return
}
// formatHeader 格式化header
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:18 2024/5/31
func formatHeader(requestConfig *define.Request) {
if nil == requestConfig {
return
}
formatHeaderData := make(map[string]string)
for headerName, headerVal := range requestConfig.Header {
formatHeaderData[textproto.CanonicalMIMEHeaderKey(headerName)] = headerVal
}
requestConfig.Header = formatHeaderData
}