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

This commit is contained in:
2025-12-13 22:37:20 +08:00
parent 5b89fff39b
commit a6e591d2ee
2 changed files with 45 additions and 28 deletions

View File

@ -10,12 +10,13 @@ package implement
import (
"errors"
"fmt"
"net/http"
"strings"
"git.zhangdeman.cn/zhangdeman/consts"
"git.zhangdeman.cn/zhangdeman/network/httpclient/define"
"git.zhangdeman.cn/zhangdeman/serialize"
"github.com/tidwall/gjson"
"net/http"
"strings"
)
// Response 响应结果解析
@ -98,21 +99,35 @@ func (r *Response) fillResponseBody(reqCfg *define.Request, response *define.Res
return errors.New("response body Marshal error :" + err.Error())
}
response.Data = string(jsonByte)
if strings.ToLower(reqCfg.CodeLocation) == "header" {
if reqCfg.CodeField == "code" {
if strings.ToUpper(reqCfg.CodeLocation) == consts.ResponseDataLocationHeader.String() {
if reqCfg.CodeField == "" || reqCfg.CodeField == "code" {
response.Code = fmt.Sprintf("%v", response.HttpCode)
response.Message = response.RestyResponse.Status()
} else {
response.Code = response.RestyResponse.Header().Get(reqCfg.CodeField)
response.Message = response.RestyResponse.Header().Get(reqCfg.MessageField)
}
} else {
// 统一认为Body
response.Code = gjson.Get(response.Data, reqCfg.CodeField).String()
}
if reqCfg.MessageFieldLocation == "" {
reqCfg.MessageFieldLocation = reqCfg.CodeLocation
}
if strings.ToUpper(reqCfg.MessageFieldLocation) == consts.ResponseDataLocationBody.String() {
// header, 统一使用 http status
response.Message = response.RestyResponse.Status()
} else {
response.Message = gjson.Get(response.Data, reqCfg.MessageField).String()
}
businessData := gjson.Get(response.Data, reqCfg.DataField)
var businessData gjson.Result
if reqCfg.DataField == "" || reqCfg.DataField == consts.ResponseDataLocationBodyRoot.String() {
// 整个Body都是数据
businessData = gjson.Parse(response.Data)
} else {
businessData = gjson.Get(response.Data, reqCfg.DataField)
}
if businessData.Value() == nil {
// data为空指针, 归一化成空对象
response.Body = map[string]any{}