feat: 升级HTTP请求, 支持自定义message location 和 解析整个响应body

This commit is contained in:
2025-12-13 22:14:25 +08:00
parent 5a23821ac4
commit 793e5d6156
2 changed files with 51 additions and 25 deletions

View File

@ -9,15 +9,17 @@ package httpclient
import (
"fmt"
"git.zhangdeman.cn/gateway/httpclient/cache"
"git.zhangdeman.cn/gateway/httpclient/define"
"git.zhangdeman.cn/gateway/httpclient/validate"
"git.zhangdeman.cn/zhangdeman/serialize"
"github.com/go-resty/resty/v2"
"github.com/tidwall/gjson"
"net/http"
"strings"
"time"
"git.zhangdeman.cn/gateway/httpclient/cache"
"git.zhangdeman.cn/gateway/httpclient/define"
"git.zhangdeman.cn/gateway/httpclient/validate"
"git.zhangdeman.cn/zhangdeman/consts"
"git.zhangdeman.cn/zhangdeman/serialize"
"github.com/go-resty/resty/v2"
"github.com/tidwall/gjson"
)
// NewHttpClient 获取http client
@ -329,9 +331,31 @@ func (hc *HttpClient) fillResponseCookie(response *define.Response) {
// Date : 21:38 2024/6/5
func (hc *HttpClient) fillResponseBody(response *define.Response) {
response.Data = string(response.RestyResponse.Body())
response.Code = gjson.Get(response.Data, hc.reqConfig.CodeField).String()
response.Message = gjson.Get(response.Data, hc.reqConfig.MessageField).String()
businessData := gjson.Get(response.Data, hc.reqConfig.DataField)
if hc.reqConfig.CodeFieldLocation == consts.ResponseDataLocationBody.String() {
// 状态码位置在body
response.Code = gjson.Get(response.Data, hc.reqConfig.CodeField).String()
} else {
// 非 Body 认为是 header
response.Code = fmt.Sprintf("%v", response.HttpCode)
}
if hc.reqConfig.MessageFieldLocation == "" {
// 未单独指定 message 字段位置, 则和code 同位置
hc.reqConfig.MessageFieldLocation = hc.reqConfig.CodeFieldLocation
}
if hc.reqConfig.CodeFieldLocation == consts.ResponseDataLocationBody.String() {
// 状态码位置在body
response.Message = gjson.Get(response.Data, hc.reqConfig.MessageField).String()
} else {
// 非 Body 认为是 header
response.Message = response.RestyResponse.Status()
}
var businessData gjson.Result
if hc.reqConfig.DataField == "" || hc.reqConfig.DataField == consts.ResponseDataLocationBodyRoot.String() {
// 整个 Body 均是数据
businessData = gjson.Parse(response.Data)
} else {
businessData = gjson.Get(response.Data, hc.reqConfig.DataField)
}
if businessData.Value() == nil {
// data为空指针, 归一化成空对象
response.Body = map[string]any{}