diff --git a/httpclient/resty.go b/httpclient/resty.go index 9e10f91..987883c 100644 --- a/httpclient/resty.go +++ b/httpclient/resty.go @@ -8,6 +8,7 @@ package httpclient import ( + "fmt" "git.zhangdeman.cn/zhangdeman/consts" "git.zhangdeman.cn/zhangdeman/network/httpclient/define" "git.zhangdeman.cn/zhangdeman/serialize" @@ -19,6 +20,56 @@ import ( "strings" ) +// 初始化请求配置, 包括: +// 1. 初始化空指针 +// 2. 合并static参数 +// 3. 使用 textproto.CanonicalMIMEHeaderKey 统一格式化header key +func initRequestConfig(reqConfig *define.Request) { + if nil == reqConfig.Header { + reqConfig.Header = map[string]any{} + } + if nil == reqConfig.Body { + reqConfig.Body = map[string]any{} + } + if nil == reqConfig.Cookie { + reqConfig.Cookie = map[string]any{} + } + if reqConfig.Query == nil { + reqConfig.Query = map[string]any{} + } + if reqConfig.PathParam == nil { + reqConfig.PathParam = map[string]string{} + } + + // 合并静态参数, 传入参数与静态参数存在相同参数, 以静态参数为准 + for loc, paramTable := range reqConfig.Static { + switch strings.ToUpper(loc) { + case consts.RequestDataLocationBody.String(): + for name, val := range paramTable { + reqConfig.Body[name] = val + } + case consts.RequestDataLocationQuery.String(): + for name, val := range paramTable { + reqConfig.Query[name] = val + } + case consts.RequestDataLocationCookie.String(): + for name, val := range paramTable { + reqConfig.Cookie[name] = val + } + case consts.RequestDataLocationHeader.String(): + for name, val := range paramTable { + reqConfig.Header[name] = val + } + case consts.RequestDataLocationUriPath.String(): + for name, val := range paramTable { + reqConfig.PathParam[name] = fmt.Sprintf("%v", val) + } + } + } + + formatHeader(reqConfig) +} + // NewRestyClient 获取resty client // // Author : go_developer@163.com<白茶清欢> @@ -30,7 +81,7 @@ func NewRestyClient(reqConfig *define.Request) (*resty.Client, *resty.Request) { if nil == reqConfig { return client, request } - formatHeader(reqConfig) + initRequestConfig(reqConfig) // 初始化 + 格式化配置 client.SetAllowMethodGetPayload(true) // 配置 GET 请求允许带 Body client.SetAllowMethodDeletePayload(true) // 配置 DELETE 请求允许带 Body client.SetJSONEscapeHTML(true) // 处理html实体字符