72 lines
1.8 KiB
Go
72 lines
1.8 KiB
Go
|
package common
|
|||
|
|
|||
|
import (
|
|||
|
"tianyuan-api/pkg/errs"
|
|||
|
|
|||
|
"github.com/bytedance/sonic"
|
|||
|
"github.com/tidwall/gjson"
|
|||
|
"github.com/zeromicro/go-zero/core/logx"
|
|||
|
)
|
|||
|
|
|||
|
// ParseWestResponse 解析西部返回的响应数据(获取data字段后解析)
|
|||
|
// westResp: 西部返回的原始响应
|
|||
|
// Returns: 解析后的数据字节数组
|
|||
|
func ParseWestResponse(westResp []byte) ([]byte, *errs.AppError) {
|
|||
|
dataResult := gjson.GetBytes(westResp, "data")
|
|||
|
if !dataResult.Exists() {
|
|||
|
return nil, errs.ErrSystem
|
|||
|
}
|
|||
|
return ParseJsonResponse([]byte(dataResult.Raw))
|
|||
|
}
|
|||
|
|
|||
|
// ParseJsonResponse 直接解析JSON响应数据
|
|||
|
// jsonResp: JSON响应数据
|
|||
|
// Returns: 解析后的数据字节数组
|
|||
|
func ParseJsonResponse(jsonResp []byte) ([]byte, *errs.AppError) {
|
|||
|
parseResult, err := RecursiveParse(string(jsonResp))
|
|||
|
if err != nil {
|
|||
|
logx.Errorf("递归反序列化失败:%v", err)
|
|||
|
return nil, errs.ErrSystem
|
|||
|
}
|
|||
|
|
|||
|
resultResp, marshalErr := sonic.Marshal(parseResult)
|
|||
|
if marshalErr != nil {
|
|||
|
logx.Errorf("序列化失败:%v", marshalErr)
|
|||
|
return nil, errs.NewAppError(errs.ErrSystem.Code, marshalErr.Error())
|
|||
|
}
|
|||
|
|
|||
|
return resultResp, nil
|
|||
|
}
|
|||
|
|
|||
|
// RecursiveParse 递归解析JSON数据
|
|||
|
func RecursiveParse(data interface{}) (interface{}, *errs.AppError) {
|
|||
|
switch v := data.(type) {
|
|||
|
case string:
|
|||
|
var parsed interface{}
|
|||
|
if err := sonic.Unmarshal([]byte(v), &parsed); err == nil {
|
|||
|
return RecursiveParse(parsed)
|
|||
|
}
|
|||
|
return v, nil
|
|||
|
case map[string]interface{}:
|
|||
|
for key, val := range v {
|
|||
|
parsed, err := RecursiveParse(val)
|
|||
|
if err != nil {
|
|||
|
return nil, err
|
|||
|
}
|
|||
|
v[key] = parsed
|
|||
|
}
|
|||
|
return v, nil
|
|||
|
case []interface{}:
|
|||
|
for i, item := range v {
|
|||
|
parsed, err := RecursiveParse(item)
|
|||
|
if err != nil {
|
|||
|
return nil, err
|
|||
|
}
|
|||
|
v[i] = parsed
|
|||
|
}
|
|||
|
return v, nil
|
|||
|
default:
|
|||
|
return v, nil
|
|||
|
}
|
|||
|
}
|