This commit is contained in:
2025-08-27 22:19:19 +08:00
parent 4031277a91
commit 5051aea55c
93 changed files with 2025 additions and 1168 deletions

View File

@@ -41,15 +41,19 @@ type ApiApplicationService interface {
// 加密参数接口
EncryptParams(ctx context.Context, userID string, cmd *commands.EncryptCommand) (string, error)
// 解密参数接口
DecryptParams(ctx context.Context, userID string, cmd *commands.DecryptCommand) (map[string]interface{}, error)
// 获取表单配置
GetFormConfig(ctx context.Context, apiCode string) (*dto.FormConfigResponse, error)
}
type ApiApplicationServiceImpl struct {
apiCallService services.ApiCallAggregateService
apiUserService services.ApiUserAggregateService
apiRequestService *services.ApiRequestService
formConfigService services.FormConfigService
apiCallRepository repositories.ApiCallRepository
walletService finance_services.WalletAggregateService
contractInfoService user_repositories.ContractInfoRepository
@@ -61,8 +65,8 @@ type ApiApplicationServiceImpl struct {
logger *zap.Logger
}
func NewApiApplicationService(apiCallService services.ApiCallAggregateService, apiUserService services.ApiUserAggregateService, apiRequestService *services.ApiRequestService, apiCallRepository repositories.ApiCallRepository, walletService finance_services.WalletAggregateService, productManagementService *product_services.ProductManagementService, productSubscriptionService *product_services.ProductSubscriptionService, userRepo user_repositories.UserRepository, txManager *database.TransactionManager, config *config.Config, logger *zap.Logger, contractInfoService user_repositories.ContractInfoRepository) ApiApplicationService {
return &ApiApplicationServiceImpl{apiCallService: apiCallService, apiUserService: apiUserService, apiRequestService: apiRequestService, apiCallRepository: apiCallRepository, walletService: walletService, productManagementService: productManagementService, productSubscriptionService: productSubscriptionService, userRepo: userRepo, txManager: txManager, config: config, logger: logger, contractInfoService: contractInfoService}
func NewApiApplicationService(apiCallService services.ApiCallAggregateService, apiUserService services.ApiUserAggregateService, apiRequestService *services.ApiRequestService, formConfigService services.FormConfigService, apiCallRepository repositories.ApiCallRepository, walletService finance_services.WalletAggregateService, productManagementService *product_services.ProductManagementService, productSubscriptionService *product_services.ProductSubscriptionService, userRepo user_repositories.UserRepository, txManager *database.TransactionManager, config *config.Config, logger *zap.Logger, contractInfoService user_repositories.ContractInfoRepository) ApiApplicationService {
return &ApiApplicationServiceImpl{apiCallService: apiCallService, apiUserService: apiUserService, apiRequestService: apiRequestService, formConfigService: formConfigService, apiCallRepository: apiCallRepository, walletService: walletService, productManagementService: productManagementService, productSubscriptionService: productSubscriptionService, userRepo: userRepo, txManager: txManager, config: config, logger: logger, contractInfoService: contractInfoService}
}
// CallApi 应用服务层统一入口
@@ -111,8 +115,8 @@ func (s *ApiApplicationServiceImpl) CallApi(ctx context.Context, cmd *commands.A
}
// 在开发环境或调试模式下跳过IP白名单校验
if s.config.App.IsDevelopment() || cmd.Options.IsDebug {
s.logger.Info("跳过IP白名单校验",
zap.String("userId", apiUser.UserId),
s.logger.Info("跳过IP白名单校验",
zap.String("userId", apiUser.UserId),
zap.String("ip", cmd.ClientIP),
zap.Bool("isDevelopment", s.config.App.IsDevelopment()),
zap.Bool("isDebug", cmd.Options.IsDebug))
@@ -176,10 +180,10 @@ func (s *ApiApplicationServiceImpl) CallApi(ctx context.Context, cmd *commands.A
callContext := &processors.CallContext{
ContractCode: contractCode,
}
// 将transactionId放入ctx中供外部服务使用
ctxWithTransactionId := context.WithValue(txCtx, "transaction_id", transactionId)
response, err := s.apiRequestService.PreprocessRequestApi(ctxWithTransactionId, cmd.ApiName, requestParams, &cmd.Options, callContext)
if err != nil {
if errors.Is(err, processors.ErrDatasource) {
@@ -527,7 +531,7 @@ func (s *ApiApplicationServiceImpl) EncryptParams(ctx context.Context, userID st
s.logger.Error("序列化参数失败", zap.Error(err))
return "", err
}
// 2. 使用前端传来的SecretKey进行加密
encryptedData, err := crypto.AesEncrypt(jsonData, cmd.SecretKey)
if err != nil {
@@ -546,7 +550,7 @@ func (s *ApiApplicationServiceImpl) DecryptParams(ctx context.Context, userID st
s.logger.Error("解密参数失败", zap.Error(err))
return nil, err
}
// 2. 将解密后的JSON字节数组转换为map
var result map[string]interface{}
err = json.Unmarshal(decryptedData, &result)
@@ -557,3 +561,38 @@ func (s *ApiApplicationServiceImpl) DecryptParams(ctx context.Context, userID st
return result, nil
}
// GetFormConfig 获取指定API的表单配置
func (s *ApiApplicationServiceImpl) GetFormConfig(ctx context.Context, apiCode string) (*dto.FormConfigResponse, error) {
// 调用领域服务获取表单配置
config, err := s.formConfigService.GetFormConfig(apiCode)
if err != nil {
s.logger.Error("获取表单配置失败", zap.String("api_code", apiCode), zap.Error(err))
return nil, err
}
if config == nil {
return nil, nil
}
// 转换为应用层DTO
response := &dto.FormConfigResponse{
ApiCode: config.ApiCode,
Fields: make([]dto.FormField, len(config.Fields)),
}
for i, field := range config.Fields {
response.Fields[i] = dto.FormField{
Name: field.Name,
Label: field.Label,
Type: field.Type,
Required: field.Required,
Validation: field.Validation,
Description: field.Description,
Example: field.Example,
Placeholder: field.Placeholder,
}
}
return response, nil
}

View File

@@ -0,0 +1,19 @@
package dto
// FormField 表单字段配置
type FormField struct {
Name string `json:"name"`
Label string `json:"label"`
Type string `json:"type"`
Required bool `json:"required"`
Validation string `json:"validation"`
Description string `json:"description"`
Example string `json:"example"`
Placeholder string `json:"placeholder"`
}
// FormConfigResponse 表单配置响应
type FormConfigResponse struct {
ApiCode string `json:"api_code"`
Fields []FormField `json:"fields"`
}

View File

@@ -583,6 +583,7 @@ func NewContainer() *Container {
api_service.NewApiUserAggregateService,
api_service.NewApiCallAggregateService,
api_service.NewApiRequestService,
api_service.NewFormConfigService,
),
// API域应用服务
@@ -712,6 +713,11 @@ func RegisterLifecycleHooks(
OnStart: func(context.Context) error {
logger.Info("应用启动中...")
logger.Info("所有依赖注入完成,开始启动应用服务")
// 确保校验器最先初始化
validator.InitGlobalValidator()
logger.Info("全局校验器初始化完成")
return nil
},
OnStop: func(context.Context) error {

View File

@@ -0,0 +1,416 @@
package services
import (
"reflect"
"strings"
"tyapi-server/internal/domains/api/dto"
)
// FormField 表单字段配置
type FormField struct {
Name string `json:"name"`
Label string `json:"label"`
Type string `json:"type"`
Required bool `json:"required"`
Validation string `json:"validation"`
Description string `json:"description"`
Example string `json:"example"`
Placeholder string `json:"placeholder"`
}
// FormConfig 表单配置
type FormConfig struct {
ApiCode string `json:"api_code"`
Fields []FormField `json:"fields"`
}
// FormConfigService 表单配置服务接口
type FormConfigService interface {
GetFormConfig(apiCode string) (*FormConfig, error)
}
// FormConfigServiceImpl 表单配置服务实现
type FormConfigServiceImpl struct{}
// NewFormConfigService 创建表单配置服务
func NewFormConfigService() FormConfigService {
return &FormConfigServiceImpl{}
}
// GetFormConfig 获取指定API的表单配置
func (s *FormConfigServiceImpl) GetFormConfig(apiCode string) (*FormConfig, error) {
// 根据API代码获取对应的DTO结构体
dtoStruct := s.getDTOStruct(apiCode)
if dtoStruct == nil {
return nil, nil
}
// 通过反射解析结构体字段
fields := s.parseDTOFields(dtoStruct)
config := &FormConfig{
ApiCode: apiCode,
Fields: fields,
}
return config, nil
}
// getDTOStruct 根据API代码获取对应的DTO结构体
func (s *FormConfigServiceImpl) getDTOStruct(apiCode string) interface{} {
// 建立API代码到DTO结构体的映射
dtoMap := map[string]interface{}{
"IVYZ9363": &dto.IVYZ9363Req{},
"IVYZ385E": &dto.IVYZ385EReq{},
"IVYZ5733": &dto.IVYZ5733Req{},
"FLXG3D56": &dto.FLXG3D56Req{},
"FLXG75FE": &dto.FLXG75FEReq{},
"FLXG0V3B": &dto.FLXG0V3BReq{},
"FLXG0V4B": &dto.FLXG0V4BReq{},
"FLXG54F5": &dto.FLXG54F5Req{},
"FLXG162A": &dto.FLXG162AReq{},
"FLXG0687": &dto.FLXG0687Req{},
"FLXG21": &dto.FLXG21Req{},
"FLXG970F": &dto.FLXG970FReq{},
"FLXG5876": &dto.FLXG5876Req{},
"FLXG9687": &dto.FLXG9687Req{},
"FLXGC9D1": &dto.FLXGC9D1Req{},
"FLXGCA3D": &dto.FLXGCA3DReq{},
"FLXGDEC7": &dto.FLXGDEC7Req{},
"JRZQ0A03": &dto.JRZQ0A03Req{},
"JRZQ4AA8": &dto.JRZQ4AA8Req{},
"JRZQ8203": &dto.JRZQ8203Req{},
"JRZQDBCE": &dto.JRZQDBCEReq{},
"QYGL2ACD": &dto.QYGL2ACDReq{},
"QYGL6F2D": &dto.QYGL6F2DReq{},
"QYGL45BD": &dto.QYGL45BDReq{},
"QYGL8261": &dto.QYGL8261Req{},
"QYGL8271": &dto.QYGL8271Req{},
"QYGLB4C0": &dto.QYGLB4C0Req{},
"QYGL23T7": &dto.QYGL23T7Req{},
"YYSY4B37": &dto.YYSY4B37Req{},
"YYSY4B21": &dto.YYSY4B21Req{},
"YYSY6F2E": &dto.YYSY6F2EReq{},
"YYSY09CD": &dto.YYSY09CDReq{},
"IVYZ0b03": &dto.IVYZ0b03Req{},
"YYSYBE08": &dto.YYSYBE08Req{},
"YYSYD50F": &dto.YYSYD50FReq{},
"YYSYF7DB": &dto.YYSYF7DBReq{},
"IVYZ9A2B": &dto.IVYZ9A2BReq{},
"IVYZ7F2A": &dto.IVYZ7F2AReq{},
"IVYZ4E8B": &dto.IVYZ4E8BReq{},
"IVYZ1C9D": &dto.IVYZ1C9DReq{},
"IVYZGZ08": &dto.IVYZGZ08Req{},
"FLXG8A3F": &dto.FLXG8A3FReq{},
"FLXG5B2E": &dto.FLXG5B2EReq{},
"COMB298Y": &dto.COMB298YReq{},
"COMB86PM": &dto.COMB86PMReq{},
"QCXG7A2B": &dto.QCXG7A2BReq{},
"COMENT01": &dto.COMENT01Req{},
"JRZQ09J8": &dto.JRZQ09J8Req{},
"FLXGDEA8": &dto.FLXGDEA8Req{},
"FLXGDEA9": &dto.FLXGDEA9Req{},
"JRZQ1D09": &dto.JRZQ1D09Req{},
"IVYZ2A8B": &dto.IVYZ2A8BReq{},
"IVYZ7C9D": &dto.IVYZ7C9DReq{},
"IVYZ5E3F": &dto.IVYZ5E3FReq{},
"YYSY4F2E": &dto.YYSY4F2EReq{},
"YYSY8B1C": &dto.YYSY8B1CReq{},
"YYSY6D9A": &dto.YYSY6D9AReq{},
"YYSY3E7F": &dto.YYSY3E7FReq{},
"FLXG5A3B": &dto.FLXG5A3BReq{},
"FLXG9C1D": &dto.FLXG9C1DReq{},
"FLXG2E8F": &dto.FLXG2E8FReq{},
"JRZQ3C7B": &dto.JRZQ3C7BReq{},
"JRZQ8A2D": &dto.JRZQ8A2DReq{},
"JRZQ5E9F": &dto.JRZQ5E9FReq{},
"JRZQ4B6C": &dto.JRZQ4B6CReq{},
"JRZQ7F1A": &dto.JRZQ7F1AReq{},
"DWBG6A2C": &dto.DWBG6A2CReq{},
"DWBG8B4D": &dto.DWBG8B4DReq{},
"FLXG8B4D": &dto.FLXG8B4DReq{},
}
return dtoMap[apiCode]
}
// parseDTOFields 通过反射解析DTO结构体字段
func (s *FormConfigServiceImpl) parseDTOFields(dtoStruct interface{}) []FormField {
var fields []FormField
t := reflect.TypeOf(dtoStruct).Elem()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
// 获取JSON标签
jsonTag := field.Tag.Get("json")
if jsonTag == "" {
continue
}
// 获取验证标签
validateTag := field.Tag.Get("validate")
// 解析验证规则
required := strings.Contains(validateTag, "required")
validation := s.parseValidationRules(validateTag)
// 根据字段类型和验证规则生成前端字段类型
fieldType := s.getFieldType(field.Type, validation)
// 生成字段标签(将下划线转换为中文)
label := s.generateFieldLabel(jsonTag)
// 生成示例值
example := s.generateExampleValue(field.Type, jsonTag)
// 生成占位符
placeholder := s.generatePlaceholder(jsonTag, fieldType)
// 生成字段描述
description := s.generateDescription(jsonTag, validation)
formField := FormField{
Name: jsonTag,
Label: label,
Type: fieldType,
Required: required,
Validation: validation,
Description: description,
Example: example,
Placeholder: placeholder,
}
fields = append(fields, formField)
}
return fields
}
// parseValidationRules 解析验证规则
func (s *FormConfigServiceImpl) parseValidationRules(validateTag string) string {
if validateTag == "" {
return ""
}
// 将验证规则转换为前端可理解的格式
rules := strings.Split(validateTag, ",")
var frontendRules []string
for _, rule := range rules {
rule = strings.TrimSpace(rule)
switch {
case rule == "required":
frontendRules = append(frontendRules, "必填")
case strings.HasPrefix(rule, "min="):
min := strings.TrimPrefix(rule, "min=")
frontendRules = append(frontendRules, "最小长度"+min)
case strings.HasPrefix(rule, "max="):
max := strings.TrimPrefix(rule, "max=")
frontendRules = append(frontendRules, "最大长度"+max)
case rule == "validMobileNo":
frontendRules = append(frontendRules, "手机号格式")
case rule == "validIDCard":
frontendRules = append(frontendRules, "身份证格式")
case rule == "validName":
frontendRules = append(frontendRules, "姓名格式")
case rule == "validUSCI":
frontendRules = append(frontendRules, "统一社会信用代码格式")
case rule == "validBankCard":
frontendRules = append(frontendRules, "银行卡号格式")
case rule == "validDate":
frontendRules = append(frontendRules, "日期格式")
case rule == "validAuthDate":
frontendRules = append(frontendRules, "授权日期格式")
case rule == "validTimeRange":
frontendRules = append(frontendRules, "时间范围格式")
case rule == "validMobileType":
frontendRules = append(frontendRules, "手机类型")
case rule == "validUniqueID":
frontendRules = append(frontendRules, "唯一标识格式")
case rule == "validReturnURL":
frontendRules = append(frontendRules, "返回链接格式")
case rule == "validAuthorizationURL":
frontendRules = append(frontendRules, "授权链接格式")
case strings.HasPrefix(rule, "oneof="):
values := strings.TrimPrefix(rule, "oneof=")
frontendRules = append(frontendRules, "可选值: "+values)
}
}
return strings.Join(frontendRules, "、")
}
// getFieldType 根据字段类型和验证规则确定前端字段类型
func (s *FormConfigServiceImpl) getFieldType(fieldType reflect.Type, validation string) string {
switch fieldType.Kind() {
case reflect.String:
if strings.Contains(validation, "手机号") {
return "tel"
} else if strings.Contains(validation, "身份证") {
return "text"
} else if strings.Contains(validation, "姓名") {
return "text"
} else if strings.Contains(validation, "日期") {
return "date"
} else if strings.Contains(validation, "链接") {
return "url"
} else if strings.Contains(validation, "可选值") {
return "select"
}
return "text"
case reflect.Int64:
return "number"
case reflect.Bool:
return "checkbox"
default:
return "text"
}
}
// generateFieldLabel 生成字段标签
func (s *FormConfigServiceImpl) generateFieldLabel(jsonTag string) string {
// 将下划线命名转换为中文标签
labelMap := map[string]string{
"mobile_no": "手机号码",
"id_card": "身份证号",
"name": "姓名",
"man_name": "男方姓名",
"woman_name": "女方姓名",
"man_id_card": "男方身份证",
"woman_id_card": "女方身份证",
"ent_name": "企业名称",
"legal_person": "法人姓名",
"ent_code": "企业代码",
"auth_date": "授权日期",
"time_range": "时间范围",
"authorized": "是否授权",
"authorization_url": "授权链接",
"unique_id": "唯一标识",
"return_url": "返回链接",
"mobile_type": "手机类型",
"start_date": "开始日期",
"years": "年数",
"bank_card": "银行卡号",
}
if label, exists := labelMap[jsonTag]; exists {
return label
}
// 如果没有预定义,尝试自动转换
return strings.ReplaceAll(jsonTag, "_", " ")
}
// generateExampleValue 生成示例值
func (s *FormConfigServiceImpl) generateExampleValue(fieldType reflect.Type, jsonTag string) string {
exampleMap := map[string]string{
"mobile_no": "13800138000",
"id_card": "110101199001011234",
"name": "张三",
"man_name": "张三",
"woman_name": "李四",
"ent_name": "示例企业有限公司",
"legal_person": "王五",
"ent_code": "91110000123456789X",
"auth_date": "2024-01-01",
"time_range": "2024-01-01至2024-12-31",
"authorized": "1",
"years": "5",
"bank_card": "6222021234567890123",
"mobile_type": "移动",
"start_date": "2024-01-01",
"unique_id": "UNIQUE123456",
"return_url": "https://example.com/return",
"authorization_url": "https://example.com/auth",
}
if example, exists := exampleMap[jsonTag]; exists {
return example
}
// 根据字段类型生成默认示例
switch fieldType.Kind() {
case reflect.String:
return "示例值"
case reflect.Int64:
return "123"
case reflect.Bool:
return "true"
default:
return "示例值"
}
}
// generatePlaceholder 生成占位符
func (s *FormConfigServiceImpl) generatePlaceholder(jsonTag string, fieldType string) string {
placeholderMap := map[string]string{
"mobile_no": "请输入11位手机号码",
"id_card": "请输入18位身份证号码",
"name": "请输入真实姓名",
"man_name": "请输入男方真实姓名",
"woman_name": "请输入女方真实姓名",
"ent_name": "请输入企业全称",
"legal_person": "请输入法人真实姓名",
"ent_code": "请输入统一社会信用代码",
"auth_date": "请选择授权日期",
"time_range": "请输入查询时间范围",
"authorized": "请选择是否授权",
"years": "请输入查询年数0-100",
"bank_card": "请输入银行卡号",
"mobile_type": "请选择手机类型",
"start_date": "请选择开始日期",
"unique_id": "请输入唯一标识",
"return_url": "请输入返回链接",
"authorization_url": "请输入授权链接",
}
if placeholder, exists := placeholderMap[jsonTag]; exists {
return placeholder
}
// 根据字段类型生成默认占位符
switch fieldType {
case "tel":
return "请输入电话号码"
case "date":
return "请选择日期"
case "url":
return "请输入链接地址"
case "number":
return "请输入数字"
default:
return "请输入" + s.generateFieldLabel(jsonTag)
}
}
// generateDescription 生成字段描述
func (s *FormConfigServiceImpl) generateDescription(jsonTag string, validation string) string {
descMap := map[string]string{
"mobile_no": "请输入11位手机号码",
"id_card": "请输入18位身份证号码",
"name": "请输入真实姓名",
"man_name": "请输入男方真实姓名",
"woman_name": "请输入女方真实姓名",
"ent_name": "请输入企业全称",
"legal_person": "请输入法人真实姓名",
"ent_code": "请输入统一社会信用代码",
"auth_date": "请输入授权日期格式YYYY-MM-DD",
"time_range": "请输入查询时间范围",
"authorized": "请输入是否授权0-未授权1-已授权",
"years": "请输入查询年数0-100",
"bank_card": "请输入银行卡号",
"mobile_type": "请选择手机类型",
"start_date": "请选择开始日期",
"unique_id": "请输入唯一标识",
"return_url": "请输入返回链接",
"authorization_url": "请输入授权链接",
}
if desc, exists := descMap[jsonTag]; exists {
return desc
}
return "请输入" + s.generateFieldLabel(jsonTag)
}

View File

@@ -0,0 +1,133 @@
package services
import (
"testing"
)
func TestFormConfigService_GetFormConfig(t *testing.T) {
service := NewFormConfigService()
// 测试获取存在的API配置
config, err := service.GetFormConfig("IVYZ9363")
if err != nil {
t.Fatalf("获取表单配置失败: %v", err)
}
if config == nil {
t.Fatal("表单配置不应为空")
}
if config.ApiCode != "IVYZ9363" {
t.Errorf("期望API代码为 IVYZ9363实际为 %s", config.ApiCode)
}
if len(config.Fields) == 0 {
t.Fatal("字段列表不应为空")
}
// 验证字段信息
expectedFields := map[string]bool{
"man_name": false,
"man_id_card": false,
"woman_name": false,
"woman_id_card": false,
}
for _, field := range config.Fields {
if _, exists := expectedFields[field.Name]; !exists {
t.Errorf("意外的字段: %s", field.Name)
}
expectedFields[field.Name] = true
}
for fieldName, found := range expectedFields {
if !found {
t.Errorf("缺少字段: %s", fieldName)
}
}
// 测试获取不存在的API配置
config, err = service.GetFormConfig("NONEXISTENT")
if err != nil {
t.Fatalf("获取不存在的API配置不应返回错误: %v", err)
}
if config != nil {
t.Fatal("不存在的API配置应返回nil")
}
}
func TestFormConfigService_FieldValidation(t *testing.T) {
service := NewFormConfigService()
config, err := service.GetFormConfig("FLXG3D56")
if err != nil {
t.Fatalf("获取表单配置失败: %v", err)
}
if config == nil {
t.Fatal("表单配置不应为空")
}
// 验证手机号字段
var mobileField *FormField
for _, field := range config.Fields {
if field.Name == "mobile_no" {
mobileField = &field
break
}
}
if mobileField == nil {
t.Fatal("应找到mobile_no字段")
}
if !mobileField.Required {
t.Error("mobile_no字段应为必填")
}
if mobileField.Type != "tel" {
t.Errorf("mobile_no字段类型应为tel实际为%s", mobileField.Type)
}
if !contains(mobileField.Validation, "手机号格式") {
t.Errorf("mobile_no字段验证规则应包含'手机号格式',实际为: %s", mobileField.Validation)
}
}
func TestFormConfigService_FieldLabels(t *testing.T) {
service := NewFormConfigService()
config, err := service.GetFormConfig("IVYZ9363")
if err != nil {
t.Fatalf("获取表单配置失败: %v", err)
}
// 验证字段标签
expectedLabels := map[string]string{
"man_name": "男方姓名",
"man_id_card": "男方身份证",
"woman_name": "女方姓名",
"woman_id_card": "女方身份证",
}
for _, field := range config.Fields {
if expectedLabel, exists := expectedLabels[field.Name]; exists {
if field.Label != expectedLabel {
t.Errorf("字段 %s 的标签应为 %s实际为 %s", field.Name, expectedLabel, field.Label)
}
}
}
}
// 辅助函数
func contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || (len(s) > len(substr) && (s[:len(substr)] == substr || s[len(s)-len(substr):] == substr || func() bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}())))
}

View File

@@ -0,0 +1,128 @@
# 处理器错误处理解决方案
## 问题描述
在使用 `errors.Join(processors.ErrInvalidParam, err)` 包装错误后,外层的 `errors.Is(err, processors.ErrInvalidParam)` 无法正确识别错误类型。
## 原因分析
`fmt.Errorf` 创建的包装错误虽然实现了 `Unwrap()` 接口,但没有实现 `Is()` 接口,因此 `errors.Is` 无法正确判断错误类型。
## 解决方案
### 🎯 **推荐方案:使用 `errors.Join`Go 1.20+**
这是最简洁、最标准的解决方案Go 1.20+ 原生支持:
```go
// 在处理器中创建错误
return nil, errors.Join(processors.ErrInvalidParam, err)
// 在应用服务层判断错误
if errors.Is(err, processors.ErrInvalidParam) {
// 现在可以正确识别了!
businessError = ErrInvalidParam
return ErrInvalidParam
}
```
### ✅ **优势**
1. **极简代码**:一行代码解决问题
2. **标准库支持**Go 1.20+ 原生功能
3. **完全兼容**`errors.Is` 可以正确识别错误类型
4. **性能优秀**:标准库实现,性能最佳
5. **向后兼容**:现有的错误处理代码无需修改
### 📝 **使用方法**
#### 在处理器中(替换旧方式):
```go
// 旧方式 ❌
return nil, errors.Join(processors.ErrInvalidParam, err)
// 新方式 ✅
return nil, errors.Join(processors.ErrInvalidParam, err)
```
#### 在应用服务层(现在可以正确工作):
```go
if errors.Is(err, processors.ErrInvalidParam) {
// 现在可以正确识别了!
businessError = ErrInvalidParam
return ErrInvalidParam
}
```
## 其他方案对比
### 方案1`errors.Join`(推荐 ⭐⭐⭐⭐⭐)
- **简洁度**:⭐⭐⭐⭐⭐
- **兼容性**:⭐⭐⭐⭐⭐
- **性能**:⭐⭐⭐⭐⭐
- **维护性**:⭐⭐⭐⭐⭐
### 方案2自定义错误类型
- **简洁度**:⭐⭐⭐
- **兼容性**:⭐⭐⭐⭐⭐
- **性能**:⭐⭐⭐⭐
- **维护性**:⭐⭐⭐
### 方案3继续使用 `fmt.Errorf`
- **简洁度**:⭐⭐⭐⭐
- **兼容性**:❌(无法识别错误类型)
- **性能**:⭐⭐⭐⭐
- **维护性**:❌
## 迁移指南
### 步骤1: 检查Go版本
确保项目使用 Go 1.20 或更高版本
### 步骤2: 更新错误创建
将所有处理器中的 `fmt.Errorf("%s: %w", processors.ErrXXX, err)` 替换为 `errors.Join(processors.ErrXXX, err)`
### 步骤3: 验证错误判断
确保应用服务层的 `errors.Is(err, processors.ErrXXX)` 能正确工作
### 步骤4: 测试验证
运行测试确保所有错误处理逻辑正常工作
## 示例
```go
// 处理器层
func ProcessRequest(ctx context.Context, params []byte, deps *ProcessorDependencies) ([]byte, error) {
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, errors.Join(processors.ErrInvalidParam, err)
}
// ... 其他逻辑
}
// 应用服务层
if err := s.apiRequestService.PreprocessRequestApi(ctx, cmd.ApiName, requestParams, &cmd.Options, callContext); err != nil {
if errors.Is(err, processors.ErrInvalidParam) {
// 现在可以正确识别了!
businessError = ErrInvalidParam
return ErrInvalidParam
}
// ... 其他错误处理
}
```
## 注意事项
1. **Go版本要求**:需要 Go 1.20 或更高版本
2. **错误消息格式**`errors.Join` 使用换行符分隔多个错误
3. **完全兼容**`errors.Is` 现在可以正确识别所有错误类型
4. **性能提升**:标准库实现,性能优于自定义解决方案
## 总结
使用 `errors.Join` 是最简洁、最标准的解决方案:
- ✅ 一行代码解决问题
- ✅ 完全兼容 `errors.Is`
- ✅ Go 1.20+ 原生支持
- ✅ 性能优秀,维护简单
如果你的项目使用 Go 1.20+,强烈推荐使用这个方案!

View File

@@ -3,7 +3,7 @@ package comb
import (
"context"
"encoding/json"
"fmt"
"errors"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -13,11 +13,11 @@ import (
func ProcessCOMB298YRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.COMB298YReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
// 调用组合包服务处理请求

View File

@@ -3,7 +3,7 @@ package comb
import (
"context"
"encoding/json"
"fmt"
"errors"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -13,11 +13,11 @@ import (
func ProcessCOMB86PMRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.COMB86PMReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
// 调用组合包服务处理请求

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,25 +14,25 @@ import (
func ProcessDWBG6A2CRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.DWBG6A2CReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
"name": encryptedName,
@@ -45,16 +44,16 @@ func ProcessDWBG6A2CRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI102", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,25 +14,25 @@ import (
func ProcessDWBG8B4DRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.DWBG8B4DReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
"name": encryptedName,
@@ -45,16 +44,16 @@ func ProcessDWBG8B4DRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI103", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -0,0 +1,91 @@
package processors
import (
"errors"
"testing"
)
func TestErrorsJoin_Is(t *testing.T) {
// 创建一个参数验证错误
originalErr := errors.New("字段验证失败")
joinedErr := errors.Join(ErrInvalidParam, originalErr)
// 测试 errors.Is 是否能正确识别错误类型
if !errors.Is(joinedErr, ErrInvalidParam) {
t.Errorf("errors.Is(joinedErr, ErrInvalidParam) 应该返回 true")
}
if errors.Is(joinedErr, ErrSystem) {
t.Errorf("errors.Is(joinedErr, ErrSystem) 应该返回 false")
}
// 测试错误消息
expectedMsg := "参数校验不正确\n字段验证失败"
if joinedErr.Error() != expectedMsg {
t.Errorf("错误消息不匹配,期望: %s, 实际: %s", expectedMsg, joinedErr.Error())
}
}
func TestErrorsJoin_Unwrap(t *testing.T) {
originalErr := errors.New("原始错误")
joinedErr := errors.Join(ErrSystem, originalErr)
// 测试 Unwrap - errors.Join 的 Unwrap 行为
// errors.Join 的 Unwrap 可能返回 nil 或者第一个错误,这取决于实现
// 我们主要关心 errors.Is 是否能正确工作
if !errors.Is(joinedErr, ErrSystem) {
t.Errorf("errors.Is(joinedErr, ErrSystem) 应该返回 true")
}
}
func TestErrorsJoin_MultipleErrors(t *testing.T) {
err1 := errors.New("错误1")
err2 := errors.New("错误2")
joinedErr := errors.Join(ErrNotFound, err1, err2)
// 测试 errors.Is 识别多个错误类型
if !errors.Is(joinedErr, ErrNotFound) {
t.Errorf("errors.Is(joinedErr, ErrNotFound) 应该返回 true")
}
// 测试错误消息
expectedMsg := "查询为空\n错误1\n错误2"
if joinedErr.Error() != expectedMsg {
t.Errorf("错误消息不匹配,期望: %s, 实际: %s", expectedMsg, joinedErr.Error())
}
}
func TestErrorsJoin_RealWorldScenario(t *testing.T) {
// 模拟真实的处理器错误场景
validationErr := errors.New("手机号格式不正确")
processorErr := errors.Join(ErrInvalidParam, validationErr)
// 在应用服务层,现在应该可以正确识别错误类型
if !errors.Is(processorErr, ErrInvalidParam) {
t.Errorf("应用服务层应该能够识别 ErrInvalidParam")
}
// 错误消息应该包含两种信息
errorMsg := processorErr.Error()
if !contains(errorMsg, "参数校验不正确") {
t.Errorf("错误消息应该包含错误类型: %s", errorMsg)
}
if !contains(errorMsg, "手机号格式不正确") {
t.Errorf("错误消息应该包含原始错误: %s", errorMsg)
}
}
// 辅助函数:检查字符串是否包含子字符串
func contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr ||
(len(s) > len(substr) && (s[:len(substr)] == substr ||
s[len(s)-len(substr):] == substr ||
func() bool {
for i := 1; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}())))
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,11 +14,11 @@ import (
func ProcessFLXG0687Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG0687Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
@@ -31,9 +30,9 @@ func ProcessFLXG0687Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.YushanService.CallAPI(ctx, "RIS031", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessFLXG0V3Bequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG0V3BReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -42,9 +41,9 @@ func ProcessFLXG0V3Bequest(ctx context.Context, params []byte, deps *processors.
respBytes, err := deps.WestDexService.CallAPI(ctx, "G34BJ03", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -18,28 +18,28 @@ import (
func ProcessFLXG0V4BRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG0V4BReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if deps.CallContext.ContractCode == "" {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, errors.New("合同编号不能为空"))
}
encryptedAuthAuthorizeFileCode, err := deps.WestDexService.Encrypt(deps.CallContext.ContractCode)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
"data": map[string]interface{}{
@@ -61,18 +61,18 @@ func ProcessFLXG0V4BRequest(ctx context.Context, params []byte, deps *processors
// 通过gjson获取指定路径的数据
contentResult := gjson.GetBytes(parsed, "G22SC0101.G22SC0102.content")
if contentResult.Exists() {
return []byte(contentResult.Raw), fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return []byte(contentResult.Raw), errors.Join(processors.ErrDatasource, err)
}
return parsed, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return parsed, errors.Join(processors.ErrDatasource, err)
}
// 解析失败,返回原始内容和系统错误
return respBytes, fmt.Errorf("%s: %w", processors.ErrSystem, parseErr)
}
// 没有返回内容,直接返回数据源错误
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
}
// 其他系统错误
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
// 正常返回 - 不管有没有deps.Options.Json都进行ParseJsonResponse
@@ -86,7 +86,7 @@ func ProcessFLXG0V4BRequest(ctx context.Context, params []byte, deps *processors
if contentResult.Exists() {
return []byte(contentResult.Raw), nil
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessFLXG162ARequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG162AReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -48,9 +47,9 @@ func ProcessFLXG162ARequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G32BJ05", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,25 +14,25 @@ import (
func ProcessFLXG2E8FRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG2E8FReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
"name": encryptedName,
@@ -45,16 +44,16 @@ func ProcessFLXG2E8FRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI101", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessFLXG3D56Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG3D56Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -49,7 +48,7 @@ func ProcessFLXG3D56Request(ctx context.Context, params []byte, deps *processors
if paramsDto.TimeRange != "" {
encryptedTimeRange, err := deps.WestDexService.Encrypt(paramsDto.TimeRange)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData["data"].(map[string]interface{})["time_range"] = encryptedTimeRange
}
@@ -57,9 +56,9 @@ func ProcessFLXG3D56Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G26BJ05", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,16 +14,16 @@ import (
func ProcessFLXG54F5Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG54F5Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -36,9 +35,9 @@ func ProcessFLXG54F5Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx,"G03HZ01", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,16 +14,16 @@ import (
func ProcessFLXG5876Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG5876Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -36,9 +35,9 @@ func ProcessFLXG5876Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G03XM02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessFLXG5A3BRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG5A3BReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -41,16 +40,16 @@ func ProcessFLXG5A3BRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI006", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -17,28 +17,28 @@ import (
func ProcessFLXG5B2ERequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG5B2EReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if deps.CallContext.ContractCode == "" {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, errors.New("合同编号不能为空"))
}
encryptedAuthAuthorizeFileCode, err := deps.WestDexService.Encrypt(deps.CallContext.ContractCode)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
"data": map[string]interface{}{
@@ -58,17 +58,17 @@ func ProcessFLXG5B2ERequest(ctx context.Context, params []byte, deps *processors
// 通过gjson获取指定路径的数据
contentResult := gjson.GetBytes(parsed, "G36SC0101.G36SC0102.content")
if contentResult.Exists() {
return []byte(contentResult.Raw), fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return []byte(contentResult.Raw), errors.Join(processors.ErrDatasource, err)
}
return parsed, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return parsed, errors.Join(processors.ErrDatasource, err)
}
// 解析失败,返回原始内容和系统错误
return respBytes, fmt.Errorf("%s: %w", processors.ErrSystem, parseErr)
}
// 没有返回内容,直接返回数据源错误
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
@@ -83,6 +83,6 @@ func ProcessFLXG5B2ERequest(ctx context.Context, params []byte, deps *processors
if contentResult.Exists() {
return []byte(contentResult.Raw), nil
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,11 +14,11 @@ import (
func ProcessFLXG75FERequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG75FEReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
reqData := map[string]interface{}{
@@ -31,9 +30,9 @@ func ProcessFLXG75FERequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx,"FLXG75FE", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -17,28 +17,28 @@ import (
func ProcessFLXG8A3FRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG8A3FReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if deps.CallContext.ContractCode == "" {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, errors.New("合同编号不能为空"))
}
encryptedAuthAuthorizeFileCode, err := deps.WestDexService.Encrypt(deps.CallContext.ContractCode)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
"data": map[string]interface{}{
@@ -58,17 +58,17 @@ func ProcessFLXG8A3FRequest(ctx context.Context, params []byte, deps *processors
// 通过gjson获取指定路径的数据
contentResult := gjson.GetBytes(parsed, "G37SC0101.G37SC0102.content")
if contentResult.Exists() {
return []byte(contentResult.Raw), fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return []byte(contentResult.Raw), errors.Join(processors.ErrDatasource, err)
}
return parsed, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return parsed, errors.Join(processors.ErrDatasource, err)
}
// 解析失败,返回原始内容和系统错误
return respBytes, fmt.Errorf("%s: %w", processors.ErrSystem, parseErr)
}
// 没有返回内容,直接返回数据源错误
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 正常返回 - 不管有没有deps.Options.Json都进行ParseJsonResponse
@@ -82,6 +82,6 @@ func ProcessFLXG8A3FRequest(ctx context.Context, params []byte, deps *processors
if contentResult.Exists() {
return []byte(contentResult.Raw), nil
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
}
}

View File

@@ -15,11 +15,11 @@ import (
func ProcessFLXG8B4DRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG8B4DReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
// 三选一校验MobileNo、IDCard、BankCard 必须且只能有一个
@@ -57,17 +57,17 @@ func ProcessFLXG8B4DRequest(ctx context.Context, params []byte, deps *processors
case "mobile_no":
encryptedValue, err = deps.ZhichaService.Encrypt(selectedValue)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
case "id_card":
encryptedValue, err = deps.ZhichaService.Encrypt(selectedValue)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
case "bank_card":
encryptedValue, err = deps.ZhichaService.Encrypt(selectedValue)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
@@ -88,16 +88,16 @@ func ProcessFLXG8B4DRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI027", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessFLXG9687Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG9687Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -48,9 +47,9 @@ func ProcessFLXG9687Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G31BJ05", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessFLXG970FRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG970FReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -42,9 +41,9 @@ func ProcessFLXG970FRequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "WEST00028", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessFLXG9C1DRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG9C1DReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -41,16 +40,16 @@ func ProcessFLXG9C1DRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI007", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,11 +14,11 @@ import (
func ProcessFLXGBC21Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG21Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
@@ -30,9 +29,9 @@ func ProcessFLXGBC21Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.YushanService.CallAPI(ctx, "MOB032", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessFLXGC9D1Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXGC9D1Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -48,9 +47,9 @@ func ProcessFLXGC9D1Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G30BJ05", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessFLXGCA3DRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXGCA3DReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -45,10 +44,10 @@ func ProcessFLXGCA3DRequest(ctx context.Context, params []byte, deps *processors
if respBytes != nil {
return respBytes, nil
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
}
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessFLXGDEA8Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXGDEA8Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -41,16 +40,16 @@ func ProcessFLXGDEA8Request(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI028", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessFLXGDEA9Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXGDEA9Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
"name": encryptedName,
@@ -40,16 +39,16 @@ func ProcessFLXGDEA9Request(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI005", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessFLXGDEC7Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXGDEC7Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -42,9 +41,9 @@ func ProcessFLXGDEC7Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G23BJ03", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessIVYZ0B03Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZ0b03Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -42,9 +41,9 @@ func ProcessIVYZ0B03Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G17BJ02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessIVYZ1C9DRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZ1C9DReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -43,9 +42,9 @@ func ProcessIVYZ1C9DRequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G38SC02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -12,11 +12,11 @@ func ProcessIVYZ2125Request(ctx context.Context, params []byte, deps *processors
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, "服务已停用")
// var paramsDto dto.IVYZ2125Req
// if err := json.Unmarshal(params, &paramsDto); err != nil {
// return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
// return nil, errors.Join(processors.ErrSystem, err)
// }
// if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
// return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
// return nil, errors.Join(processors.ErrInvalidParam, err)
// }
// reqData := map[string]interface{}{
@@ -28,9 +28,9 @@ func ProcessIVYZ2125Request(ctx context.Context, params []byte, deps *processors
// respBytes, err := deps.WestDexService.CallAPI(ctx, "IVYZ2125", reqData)
// if err != nil {
// if errors.Is(err, westdex.ErrDatasource) {
// return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
// return nil, errors.Join(processors.ErrDatasource, err)
// } else {
// return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
// return nil, errors.Join(processors.ErrSystem, err)
// }
// }

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessIVYZ2A8BRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZ2A8BReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -41,16 +40,16 @@ func ProcessIVYZ2A8BRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI001", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessIVYZ385ERequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZ385EReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -40,9 +39,9 @@ func ProcessIVYZ385ERequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "WEST00020", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -17,21 +17,21 @@ import (
func ProcessIVYZ4E8BRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZ4E8BReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -44,16 +44,16 @@ func ProcessIVYZ4E8BRequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G09GZ02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 解析响应提取data字段中的hyzk
var respMap map[string]interface{}
if err := json.Unmarshal(respBytes, &respMap); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
dataStr, ok := respMap["data"].(string)
@@ -77,7 +77,7 @@ func ProcessIVYZ4E8BRequest(ctx context.Context, params []byte, deps *processors
}
finalBytes, err := json.Marshal(resp)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return finalBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessIVYZ5733Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZ5733Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -42,9 +41,9 @@ func ProcessIVYZ5733Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G09XM02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessIVYZ5E3FRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZ5E3FReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -41,16 +40,16 @@ func ProcessIVYZ5E3FRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI029", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,11 +14,11 @@ import (
func ProcessIVYZ7C9DRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZ7C9DReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
reqData := map[string]interface{}{
@@ -32,16 +31,16 @@ func ProcessIVYZ7C9DRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI013", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -17,31 +17,31 @@ import (
func ProcessIVYZ7F2ARequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZ7F2AReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedManName, err := deps.WestDexService.Encrypt(paramsDto.ManName)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedManIDCard, err := deps.WestDexService.Encrypt(paramsDto.ManIDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedWomanName, err := deps.WestDexService.Encrypt(paramsDto.WomanName)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedWomanIDCard, err := deps.WestDexService.Encrypt(paramsDto.WomanIDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -56,14 +56,14 @@ func ProcessIVYZ7F2ARequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G10GZ02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
var respMap map[string]interface{}
if err := json.Unmarshal(respBytes, &respMap); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
dataStr, ok := respMap["data"].(string)
@@ -87,7 +87,7 @@ func ProcessIVYZ7F2ARequest(ctx context.Context, params []byte, deps *processors
}
finalBytes, err := json.Marshal(resp)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return finalBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,31 +14,31 @@ import (
func ProcessIVYZ9363Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZ9363Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedManName, err := deps.WestDexService.Encrypt(paramsDto.ManName)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedManIDCard, err := deps.WestDexService.Encrypt(paramsDto.ManIDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedWomanName, err := deps.WestDexService.Encrypt(paramsDto.WomanName)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedWomanIDCard, err := deps.WestDexService.Encrypt(paramsDto.WomanIDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -54,9 +53,9 @@ func ProcessIVYZ9363Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G10XM02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessIVYZ9A2BRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZ9A2BReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -42,9 +41,9 @@ func ProcessIVYZ9A2BRequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G11BJ06", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -12,11 +12,11 @@ func ProcessIVYZADEERequest(ctx context.Context, params []byte, deps *processors
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, "服务已停用")
// var paramsDto dto.IVYZADEEReq
// if err := json.Unmarshal(params, &paramsDto); err != nil {
// return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
// return nil, errors.Join(processors.ErrSystem, err)
// }
// if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
// return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
// return nil, errors.Join(processors.ErrInvalidParam, err)
// }
// reqData := map[string]interface{}{
@@ -28,9 +28,9 @@ func ProcessIVYZADEERequest(ctx context.Context, params []byte, deps *processors
// respBytes, err := deps.WestDexService.CallAPI(ctx, "IVYZADEE", reqData)
// if err != nil {
// if errors.Is(err, westdex.ErrDatasource) {
// return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
// return nil, errors.Join(processors.ErrDatasource, err)
// } else {
// return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
// return nil, errors.Join(processors.ErrSystem, err)
// }
// }

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessIVYZGZ08Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.IVYZGZ08Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -42,9 +41,9 @@ func ProcessIVYZGZ08Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G08SC02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessJRZQ09J8Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.JRZQ09J8Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -47,16 +46,16 @@ func ProcessJRZQ09J8Request(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI031", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessJRZQ0A03Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.JRZQ0A03Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -48,9 +47,9 @@ func ProcessJRZQ0A03Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G27BJ05", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessJRZQ1D09Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.JRZQ1D09Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -47,16 +46,16 @@ func ProcessJRZQ1D09Request(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI020", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessJRZQ3C7BRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.JRZQ3C7BReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -47,16 +46,16 @@ func ProcessJRZQ3C7BRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI017", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessJRZQ4AA8Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.JRZQ4AA8Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -48,9 +47,9 @@ func ProcessJRZQ4AA8Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G29BJ05", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessJRZQ4B6CRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.JRZQ4B6CReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -47,16 +46,16 @@ func ProcessJRZQ4B6CRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI023", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessJRZQ5E9FRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.JRZQ5E9FReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -47,16 +46,16 @@ func ProcessJRZQ5E9FRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI021", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessJRZQ7F1ARequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.JRZQ7F1AReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -47,16 +46,16 @@ func ProcessJRZQ7F1ARequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI008", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessJRZQ8203Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.JRZQ8203Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -48,9 +47,9 @@ func ProcessJRZQ8203Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G28BJ05", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessJRZQ8A2DRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.JRZQ8A2DReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -47,16 +46,16 @@ func ProcessJRZQ8A2DRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI018", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,31 +14,31 @@ import (
func ProcessJRZQDCBERequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.JRZQDBCEReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedBankCard, err := deps.WestDexService.Encrypt(paramsDto.BankCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -54,9 +53,9 @@ func ProcessJRZQDCBERequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G20GZ01", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,11 +14,11 @@ import (
func ProcessQCXG7A2BRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.QCXG7A2BReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
reqData := map[string]interface{}{
@@ -29,9 +28,9 @@ func ProcessQCXG7A2BRequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.YushanService.CallAPI(ctx, "CAR061", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -3,6 +3,7 @@ package qygl
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@@ -16,11 +17,11 @@ import (
func ProcessCOMENT01Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.COMENT01Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
// 构建请求体
@@ -31,14 +32,14 @@ func ProcessCOMENT01Request(ctx context.Context, params []byte, deps *processors
requestBodyBytes, err := json.Marshal(requestBody)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
// 创建HTTP请求
url := "https://api.v1.tybigdata.com/api/v1/enterprise/risk-report"
req, err := http.NewRequestWithContext(ctx, "POST", url, strings.NewReader(string(requestBodyBytes)))
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
// 设置请求头
@@ -49,7 +50,7 @@ func ProcessCOMENT01Request(ctx context.Context, params []byte, deps *processors
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
}
defer resp.Body.Close()
@@ -61,7 +62,7 @@ func ProcessCOMENT01Request(ctx context.Context, params []byte, deps *processors
// 读取响应
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBody, nil

View File

@@ -3,6 +3,7 @@ package qygl
import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
@@ -15,11 +16,11 @@ import (
func ProcessQYGL23T7Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.QYGL23T7Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
// 构建API调用参数
@@ -33,9 +34,9 @@ func ProcessQYGL23T7Request(ctx context.Context, params []byte, deps *processors
response, err := deps.TianYanChaService.CallAPI(ctx, "VerifyThreeElements", apiParams)
if err != nil {
if err.Error() == "数据源异常" { // Specific error handling for data source issues
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
@@ -81,7 +82,7 @@ func ProcessQYGL23T7Request(ctx context.Context, params []byte, deps *processors
// 调用阿里云二要素验证API
respBytes, err := deps.AlicloudService.CallAPI("api-mall/api/id_card/check", reqData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
// 解析阿里云响应
@@ -100,7 +101,7 @@ func ProcessQYGL23T7Request(ctx context.Context, params []byte, deps *processors
}
if err := json.Unmarshal(respBytes, &alicloudResponse); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
// 检查响应状态

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessQYGL2ACDRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.QYGL2ACDReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedEntName, err := deps.WestDexService.Encrypt(paramsDto.EntName)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedLegalPerson, err := deps.WestDexService.Encrypt(paramsDto.LegalPerson)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedEntCode, err := deps.WestDexService.Encrypt(paramsDto.EntCode)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -48,9 +47,9 @@ func ProcessQYGL2ACDRequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "WEST00022", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,31 +14,31 @@ import (
func ProcessQYGL45BDRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.QYGL45BDReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedEntName, err := deps.WestDexService.Encrypt(paramsDto.EntName)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedLegalPerson, err := deps.WestDexService.Encrypt(paramsDto.LegalPerson)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedEntCode, err := deps.WestDexService.Encrypt(paramsDto.EntCode)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -57,9 +56,9 @@ func ProcessQYGL45BDRequest(ctx context.Context, params []byte, deps *processors
if respBytes != nil {
return respBytes,nil
}
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,16 +14,16 @@ import (
func ProcessQYGL6F2DRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.QYGL6F2DReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -36,9 +35,9 @@ func ProcessQYGL6F2DRequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G05XM02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,16 +14,16 @@ import (
func ProcessQYGL8261Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.QYGL8261Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedEntName, err := deps.WestDexService.Encrypt(paramsDto.EntName)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -36,9 +35,9 @@ func ProcessQYGL8261Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "Q03BJ03", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -17,28 +17,28 @@ import (
func ProcessQYGL8271Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.QYGL8271Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedEntName, err := deps.WestDexService.Encrypt(paramsDto.EntName)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedEntCode, err := deps.WestDexService.Encrypt(paramsDto.EntCode)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if deps.CallContext.ContractCode == "" {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, errors.New("合同编号不能为空"))
}
encryptedAuthAuthorizeFileCode, err := deps.WestDexService.Encrypt(deps.CallContext.ContractCode)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
"data": map[string]interface{}{
@@ -60,18 +60,18 @@ func ProcessQYGL8271Request(ctx context.Context, params []byte, deps *processors
// 通过gjson获取指定路径的数据
contentResult := gjson.GetBytes(parsed, "Q03SC0101.Q03SC0102.content")
if contentResult.Exists() {
return []byte(contentResult.Raw), fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return []byte(contentResult.Raw), errors.Join(processors.ErrDatasource, err)
}
return parsed, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return parsed, errors.Join(processors.ErrDatasource, err)
}
// 解析失败,返回原始内容和系统错误
return respBytes, fmt.Errorf("%s: %w", processors.ErrSystem, parseErr)
}
// 没有返回内容,直接返回数据源错误
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
}
// 其他系统错误
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
// 正常返回 - 不管有没有deps.Options.Json都进行ParseJsonResponse
@@ -85,6 +85,6 @@ func ProcessQYGL8271Request(ctx context.Context, params []byte, deps *processors
if contentResult.Exists() {
return []byte(contentResult.Raw), nil
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
}
}

View File

@@ -17,11 +17,11 @@ import (
func ProcessQYGLB4C0Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.QYGLB4C0Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedIDCard := deps.WestDexService.Md5Encrypt(paramsDto.IDCard)
@@ -42,13 +42,13 @@ func ProcessQYGLB4C0Request(ctx context.Context, params []byte, deps *processors
return nil, fmt.Errorf("%s: %w", processors.ErrNotFound, err)
}
}
return respBytes, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return respBytes, errors.Join(processors.ErrDatasource, err)
}
// 没有返回内容,直接返回数据源错误
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
}
// 其他系统错误
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessYYSY09CDRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.YYSY09CDReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -49,9 +48,9 @@ func ProcessYYSY09CDRequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G16BJ02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,16 +14,16 @@ import (
func ProcessYYSY3E7FRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.YYSY3E7FReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -34,16 +33,16 @@ func ProcessYYSY3E7FRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI010", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,16 +14,16 @@ import (
func ProcessYYSY4B21Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.YYSY4B21Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -36,9 +35,9 @@ func ProcessYYSY4B21Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G25BJ02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,16 +14,16 @@ import (
func ProcessYYSY4B37Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.YYSY4B37Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -36,9 +35,9 @@ func ProcessYYSY4B37Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G02BJ02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessYYSY4F2ERequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.YYSY4F2EReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.ZhichaService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.ZhichaService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -47,16 +46,16 @@ func ProcessYYSY4F2ERequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI002", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,16 +14,16 @@ import (
func ProcessYYSY6D9ARequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.YYSY6D9AReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -34,16 +33,16 @@ func ProcessYYSY6D9ARequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI030", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,26 +14,26 @@ import (
func ProcessYYSY6F2ERequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.YYSY6F2EReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedName, err := deps.WestDexService.Encrypt(paramsDto.Name)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -49,9 +48,9 @@ func ProcessYYSY6F2ERequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G15BJ02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,16 +14,16 @@ import (
func ProcessYYSY8B1CRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.YYSY8B1CReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedMobileNo, err := deps.ZhichaService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -34,16 +33,16 @@ func ProcessYYSY8B1CRequest(ctx context.Context, params []byte, deps *processors
respData, err := deps.ZhichaService.CallAPI(ctx, "ZCI003", reqData)
if err != nil {
if errors.Is(err, zhicha.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}
// 将响应数据转换为JSON字节
respBytes, err := json.Marshal(respData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
return respBytes, nil

View File

@@ -3,6 +3,7 @@ package yysy
import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
@@ -13,11 +14,11 @@ import (
func ProcessYYSYBE08Request(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.YYSYBE08Req
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
// 调用阿里云二要素验证API
@@ -28,7 +29,7 @@ func ProcessYYSYBE08Request(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.AlicloudService.CallAPI("api-mall/api/id_card/check", reqData)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
// 解析阿里云响应
@@ -47,7 +48,7 @@ func ProcessYYSYBE08Request(ctx context.Context, params []byte, deps *processors
}
if err := json.Unmarshal(respBytes, &alicloudResponse); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
// 检查响应状态

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,21 +14,21 @@ import (
func ProcessYYSYD50FRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.YYSYD50FReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
encryptedIDCard, err := deps.WestDexService.Encrypt(paramsDto.IDCard)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -42,9 +41,9 @@ func ProcessYYSYD50FRequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G18BJ02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"tyapi-server/internal/domains/api/dto"
"tyapi-server/internal/domains/api/services/processors"
@@ -15,16 +14,16 @@ import (
func ProcessYYSYF7DBRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.YYSYF7DBReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrInvalidParam, err)
return nil, errors.Join(processors.ErrInvalidParam, err)
}
encryptedMobileNo, err := deps.WestDexService.Encrypt(paramsDto.MobileNo)
if err != nil {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
reqData := map[string]interface{}{
@@ -37,9 +36,9 @@ func ProcessYYSYF7DBRequest(ctx context.Context, params []byte, deps *processors
respBytes, err := deps.WestDexService.CallAPI(ctx, "G19BJ02", reqData)
if err != nil {
if errors.Is(err, westdex.ErrDatasource) {
return nil, fmt.Errorf("%s: %w", processors.ErrDatasource, err)
return nil, errors.Join(processors.ErrDatasource, err)
} else {
return nil, fmt.Errorf("%s: %w", processors.ErrSystem, err)
return nil, errors.Join(processors.ErrSystem, err)
}
}

View File

@@ -0,0 +1,123 @@
# 外部服务错误处理修复说明
## 问题描述
在外部服务WestDex、Yushan、Zhicha使用 `fmt.Errorf("%w: %s", ErrXXX, err)` 包装错误后,外层的 `errors.Is(err, ErrXXX)` 无法正确识别错误类型。
## 问题原因
`fmt.Errorf` 创建的包装错误虽然实现了 `Unwrap()` 接口,但没有实现 `Is()` 接口,因此 `errors.Is` 无法正确判断错误类型。
## 修复方案
统一使用 `errors.Join` 来组合错误,这是 Go 1.20+ 的标准做法,天然支持 `errors.Is` 判断。
## 修复内容
### 1. WestDex 服务 (`westdex_service.go`)
#### 修复前:
```go
// 无法被 errors.Is 识别的错误包装
err = fmt.Errorf("%w: %s", ErrSystem, marshalErr.Error())
err = fmt.Errorf("%w: %s", ErrDatasource, westDexResp.Message)
```
#### 修复后:
```go
// 可以被 errors.Is 正确识别的错误组合
err = errors.Join(ErrSystem, marshalErr)
err = errors.Join(ErrDatasource, fmt.Errorf(westDexResp.Message))
```
### 2. Yushan 服务 (`yushan_service.go`)
#### 修复前:
```go
// 无法被 errors.Is 识别的错误包装
err = fmt.Errorf("%w: %s", ErrSystem, err.Error())
err = fmt.Errorf("%w: %s", ErrDatasource, "羽山请求retdata为空")
```
#### 修复后:
```go
// 可以被 errors.Is 正确识别的错误组合
err = errors.Join(ErrSystem, err)
err = errors.Join(ErrDatasource, fmt.Errorf("羽山请求retdata为空"))
```
### 3. Zhicha 服务 (`zhicha_service.go`)
#### 修复前:
```go
// 无法被 errors.Is 识别的错误包装
err = fmt.Errorf("%w: %s", ErrSystem, marshalErr.Error())
err = fmt.Errorf("%w: %s", ErrDatasource, "HTTP状态码 %d", response.StatusCode)
```
#### 修复后:
```go
// 可以被 errors.Is 正确识别的错误组合
err = errors.Join(ErrSystem, marshalErr)
err = errors.Join(ErrDatasource, fmt.Errorf("HTTP状态码 %d", response.StatusCode))
```
## 修复效果
### 修复前的问题:
```go
// 在应用服务层
if errors.Is(err, westdex.ErrDatasource) {
// 这里无法正确识别,因为 fmt.Errorf 包装的错误
// 没有实现 Is() 接口
return ErrDatasource
}
```
### 修复后的效果:
```go
// 在应用服务层
if errors.Is(err, westdex.ErrDatasource) {
// 现在可以正确识别了!
return ErrDatasource
}
if errors.Is(err, westdex.ErrSystem) {
// 系统错误也能正确识别
return ErrSystem
}
```
## 优势
1. **完全兼容**`errors.Is` 现在可以正确识别所有错误类型
2. **标准做法**:使用 Go 1.20+ 的 `errors.Join` 标准库功能
3. **性能优秀**:标准库实现,性能优于自定义解决方案
4. **维护简单**:无需自定义错误类型,代码更简洁
## 注意事项
1. **Go版本要求**:需要 Go 1.20 或更高版本(项目使用 Go 1.23.4,完全满足)
2. **错误消息格式**`errors.Join` 使用换行符分隔多个错误
3. **向后兼容**:现有的错误处理代码无需修改
## 测试验证
所有修复后的外部服务都能正确编译:
```bash
go build ./internal/infrastructure/external/westdex/...
go build ./internal/infrastructure/external/yushan/...
go build ./internal/infrastructure/external/zhicha/...
```
## 总结
通过统一使用 `errors.Join` 修复外部服务的错误处理,现在:
-`errors.Is(err, ErrDatasource)` 可以正确识别数据源异常
-`errors.Is(err, ErrSystem)` 可以正确识别系统异常
-`errors.Is(err, ErrNotFound)` 可以正确识别查询为空
- ✅ 错误处理逻辑更加清晰和可靠
- ✅ 符合 Go 1.20+ 的最佳实践
这个修复确保了整个系统的错误处理链路都能正确工作,提高了系统的可靠性和可维护性。

View File

@@ -99,7 +99,7 @@ func (w *WestDexService) CallAPI(ctx context.Context, code string, reqData map[s
jsonData, marshalErr := json.Marshal(reqData)
if marshalErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, marshalErr.Error())
err = errors.Join(ErrSystem, marshalErr)
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
}
@@ -109,7 +109,7 @@ func (w *WestDexService) CallAPI(ctx context.Context, code string, reqData map[s
// 创建HTTP POST请求
req, newRequestErr := http.NewRequestWithContext(ctx, "POST", reqUrl, bytes.NewBuffer(jsonData))
if newRequestErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, newRequestErr.Error())
err = errors.Join(ErrSystem, newRequestErr)
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
}
@@ -123,7 +123,7 @@ func (w *WestDexService) CallAPI(ctx context.Context, code string, reqData map[s
client := &http.Client{}
httpResp, clientDoErr := client.Do(req)
if clientDoErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, clientDoErr.Error())
err = errors.Join(ErrSystem, clientDoErr)
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
}
@@ -134,7 +134,7 @@ func (w *WestDexService) CallAPI(ctx context.Context, code string, reqData map[s
if closeErr != nil {
// 记录关闭错误
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, fmt.Errorf("关闭响应体失败: %w", closeErr), reqData)
w.logger.LogError(requestID, transactionID, code, errors.Join(ErrSystem, fmt.Errorf("关闭响应体失败: %w", closeErr)), reqData)
}
}
}(httpResp.Body)
@@ -147,7 +147,7 @@ func (w *WestDexService) CallAPI(ctx context.Context, code string, reqData map[s
// 读取响应体
bodyBytes, ReadErr := io.ReadAll(httpResp.Body)
if ReadErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, ReadErr.Error())
err = errors.Join(ErrSystem, ReadErr)
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
}
@@ -158,7 +158,7 @@ func (w *WestDexService) CallAPI(ctx context.Context, code string, reqData map[s
var westDexResp WestResp
UnmarshalErr := json.Unmarshal(bodyBytes, &westDexResp)
if UnmarshalErr != nil {
err = UnmarshalErr
err = errors.Join(ErrSystem, UnmarshalErr)
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
}
@@ -172,7 +172,7 @@ func (w *WestDexService) CallAPI(ctx context.Context, code string, reqData map[s
if westDexResp.Code != "00000" && westDexResp.Code != "200" && westDexResp.Code != "0" {
if westDexResp.Data == "" {
err = fmt.Errorf("%w: %s", ErrSystem, westDexResp.Message)
err = errors.Join(ErrSystem, fmt.Errorf(westDexResp.Message))
if w.logger != nil {
w.logger.LogErrorWithResponseID(requestID, transactionID, code, err, reqData, westDexResp.ID)
}
@@ -180,7 +180,7 @@ func (w *WestDexService) CallAPI(ctx context.Context, code string, reqData map[s
}
decryptedData, DecryptErr := crypto.WestDexDecrypt(westDexResp.Data, w.config.Key)
if DecryptErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, DecryptErr.Error())
err = errors.Join(ErrSystem, DecryptErr)
if w.logger != nil {
w.logger.LogErrorWithResponseID(requestID, transactionID, code, err, reqData, westDexResp.ID)
}
@@ -189,17 +189,17 @@ func (w *WestDexService) CallAPI(ctx context.Context, code string, reqData map[s
// 记录业务错误日志包含响应ID
if w.logger != nil {
w.logger.LogErrorWithResponseID(requestID, transactionID, code, fmt.Errorf("%w: %s", ErrDatasource, westDexResp.Message), reqData, westDexResp.ID)
w.logger.LogErrorWithResponseID(requestID, transactionID, code, errors.Join(ErrDatasource, fmt.Errorf(westDexResp.Message)), reqData, westDexResp.ID)
}
// 记录性能日志(失败)
// 注意:通用日志系统不包含性能日志功能
return decryptedData, fmt.Errorf("%w: %s", ErrDatasource, westDexResp.Message)
return decryptedData, errors.Join(ErrDatasource, fmt.Errorf(westDexResp.Message))
}
if westDexResp.Data == "" {
err = fmt.Errorf("%w: %s", ErrSystem, westDexResp.Message)
err = errors.Join(ErrSystem, fmt.Errorf(westDexResp.Message))
if w.logger != nil {
w.logger.LogErrorWithResponseID(requestID, transactionID, code, err, reqData, westDexResp.ID)
}
@@ -208,7 +208,7 @@ func (w *WestDexService) CallAPI(ctx context.Context, code string, reqData map[s
decryptedData, DecryptErr := crypto.WestDexDecrypt(westDexResp.Data, w.config.Key)
if DecryptErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, DecryptErr.Error())
err = errors.Join(ErrSystem, DecryptErr)
if w.logger != nil {
w.logger.LogErrorWithResponseID(requestID, transactionID, code, err, reqData, westDexResp.ID)
}
@@ -222,7 +222,7 @@ func (w *WestDexService) CallAPI(ctx context.Context, code string, reqData map[s
}
// 记录HTTP错误
err = fmt.Errorf("%w: 西部请求失败Code: %d", ErrSystem, httpResp.StatusCode)
err = errors.Join(ErrSystem, fmt.Errorf("西部请求失败Code: %d", httpResp.StatusCode))
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
// 注意:通用日志系统不包含性能日志功能
@@ -252,7 +252,7 @@ func (w *WestDexService) G05HZ01CallAPI(ctx context.Context, code string, reqDat
jsonData, marshalErr := json.Marshal(reqData)
if marshalErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, marshalErr.Error())
err = errors.Join(ErrSystem, marshalErr)
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
}
@@ -262,7 +262,7 @@ func (w *WestDexService) G05HZ01CallAPI(ctx context.Context, code string, reqDat
// 创建HTTP POST请求
req, newRequestErr := http.NewRequestWithContext(ctx, "POST", reqUrl, bytes.NewBuffer(jsonData))
if newRequestErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, newRequestErr.Error())
err = errors.Join(ErrSystem, newRequestErr)
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
}
@@ -276,7 +276,7 @@ func (w *WestDexService) G05HZ01CallAPI(ctx context.Context, code string, reqDat
client := &http.Client{}
httpResp, clientDoErr := client.Do(req)
if clientDoErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, clientDoErr.Error())
err = errors.Join(ErrSystem, clientDoErr)
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
}
@@ -287,7 +287,7 @@ func (w *WestDexService) G05HZ01CallAPI(ctx context.Context, code string, reqDat
if closeErr != nil {
// 记录关闭错误
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, fmt.Errorf("关闭响应体失败: %w", closeErr), reqData)
w.logger.LogError(requestID, transactionID, code, errors.Join(ErrSystem, fmt.Errorf("关闭响应体失败: %w", closeErr)), reqData)
}
}
}(httpResp.Body)
@@ -298,7 +298,7 @@ func (w *WestDexService) G05HZ01CallAPI(ctx context.Context, code string, reqDat
if httpResp.StatusCode == 200 {
bodyBytes, ReadErr := io.ReadAll(httpResp.Body)
if ReadErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, ReadErr.Error())
err = errors.Join(ErrSystem, ReadErr)
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
}
@@ -308,7 +308,7 @@ func (w *WestDexService) G05HZ01CallAPI(ctx context.Context, code string, reqDat
var westDexResp G05HZ01WestResp
UnmarshalErr := json.Unmarshal(bodyBytes, &westDexResp)
if UnmarshalErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, UnmarshalErr.Error())
err = errors.Join(ErrSystem, UnmarshalErr)
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
}
@@ -322,7 +322,7 @@ func (w *WestDexService) G05HZ01CallAPI(ctx context.Context, code string, reqDat
if westDexResp.Code != "0000" {
if westDexResp.Data == nil {
err = fmt.Errorf("%w: %s", ErrSystem, westDexResp.Message)
err = errors.Join(ErrSystem, fmt.Errorf(westDexResp.Message))
if w.logger != nil {
w.logger.LogErrorWithResponseID(requestID, transactionID, code, err, reqData, westDexResp.ID)
}
@@ -330,18 +330,18 @@ func (w *WestDexService) G05HZ01CallAPI(ctx context.Context, code string, reqDat
} else {
// 记录业务错误日志包含响应ID
if w.logger != nil {
w.logger.LogErrorWithResponseID(requestID, transactionID, code, fmt.Errorf("%w: %s", ErrSystem, string(westDexResp.Data)), reqData, westDexResp.ID)
w.logger.LogErrorWithResponseID(requestID, transactionID, code, errors.Join(ErrSystem, fmt.Errorf(string(westDexResp.Data))), reqData, westDexResp.ID)
}
// 记录性能日志(失败)
// 注意:通用日志系统不包含性能日志功能
return westDexResp.Data, fmt.Errorf("%w: %s", ErrSystem, string(westDexResp.Data))
return westDexResp.Data, errors.Join(ErrSystem, fmt.Errorf(string(westDexResp.Data)))
}
}
if westDexResp.Data == nil {
err = fmt.Errorf("%w: %s", ErrSystem, westDexResp.Message)
err = errors.Join(ErrSystem, fmt.Errorf(westDexResp.Message))
if w.logger != nil {
w.logger.LogErrorWithResponseID(requestID, transactionID, code, err, reqData, westDexResp.ID)
}
@@ -354,7 +354,7 @@ func (w *WestDexService) G05HZ01CallAPI(ctx context.Context, code string, reqDat
return westDexResp.Data, nil
} else {
// 记录HTTP错误
err = fmt.Errorf("%w: 西部请求失败Code: %d", ErrSystem, httpResp.StatusCode)
err = errors.Join(ErrSystem, fmt.Errorf("西部请求失败Code: %d", httpResp.StatusCode))
if w.logger != nil {
w.logger.LogError(requestID, transactionID, code, err, reqData)
// 注意:通用日志系统不包含性能日志功能

View File

@@ -84,7 +84,7 @@ func (y *YushanService) CallAPI(ctx context.Context, code string, params map[str
// 将请求数据转换为 JSON 字节数组
messageBytes, err := json.Marshal(reqData)
if err != nil {
err = fmt.Errorf("%w: %s", ErrSystem, err.Error())
err = errors.Join(ErrSystem, err)
if y.logger != nil {
y.logger.LogError(requestID, transactionID, code, err, params)
}
@@ -94,7 +94,7 @@ func (y *YushanService) CallAPI(ctx context.Context, code string, params map[str
// 获取 API 密钥
key, err := hex.DecodeString(y.config.ApiKey)
if err != nil {
err = fmt.Errorf("%w: %s", ErrSystem, err.Error())
err = errors.Join(ErrSystem, err)
if y.logger != nil {
y.logger.LogError(requestID, transactionID, code, err, params)
}
@@ -113,7 +113,7 @@ func (y *YushanService) CallAPI(ctx context.Context, code string, params map[str
}
req, err := http.NewRequestWithContext(ctx, "POST", y.config.URL, strings.NewReader(content))
if err != nil {
err = fmt.Errorf("%w: %s", ErrSystem, err.Error())
err = errors.Join(ErrSystem, err)
if y.logger != nil {
y.logger.LogError(requestID, transactionID, code, err, params)
}
@@ -125,7 +125,7 @@ func (y *YushanService) CallAPI(ctx context.Context, code string, params map[str
// 执行请求
resp, err := client.Do(req)
if err != nil {
err = fmt.Errorf("%w: %s", ErrSystem, err.Error())
err = errors.Join(ErrSystem, err)
if y.logger != nil {
y.logger.LogError(requestID, transactionID, code, err, params)
}
@@ -149,7 +149,7 @@ func (y *YushanService) CallAPI(ctx context.Context, code string, params map[str
} else {
sDec, err := base64.StdEncoding.DecodeString(string(body))
if err != nil {
err = fmt.Errorf("%w: %s", ErrSystem, err.Error())
err = errors.Join(ErrSystem, err)
if y.logger != nil {
y.logger.LogError(requestID, transactionID, code, err, params)
}
@@ -172,7 +172,7 @@ func (y *YushanService) CallAPI(ctx context.Context, code string, params map[str
// retcode 为 000000表示有数据返回 retdata
retData := gjson.GetBytes(respData, "retdata")
if !retData.Exists() {
err = fmt.Errorf("%w: %s", ErrDatasource, "羽山请求retdata为空")
err = errors.Join(ErrDatasource, fmt.Errorf("羽山请求retdata为空"))
if y.logger != nil {
y.logger.LogError(requestID, transactionID, code, err, params)
}
@@ -180,7 +180,7 @@ func (y *YushanService) CallAPI(ctx context.Context, code string, params map[str
}
return []byte(retData.Raw), nil
} else {
err = fmt.Errorf("%w: %s", ErrDatasource, "羽山请求未知的状态码")
err = errors.Join(ErrDatasource, fmt.Errorf("羽山请求未知的状态码"))
if y.logger != nil {
y.logger.LogError(requestID, transactionID, code, err, params)
}

View File

@@ -34,7 +34,7 @@ type ZhichaResp struct {
type ZhichaConfig struct {
URL string
AppID string
AppSecret string
AppSecret string
EncryptKey string
}
@@ -94,7 +94,7 @@ func (z *ZhichaService) CallAPI(ctx context.Context, proID string, params map[st
jsonData, marshalErr := json.Marshal(params)
if marshalErr != nil {
err = fmt.Errorf("%w: %s", ErrSystem, marshalErr.Error())
err = errors.Join(ErrSystem, marshalErr)
if z.logger != nil {
z.logger.LogError(requestID, transactionID, proID, err, params)
}
@@ -104,7 +104,7 @@ func (z *ZhichaService) CallAPI(ctx context.Context, proID string, params map[st
// 创建HTTP POST请求
req, err := http.NewRequestWithContext(ctx, "POST", z.config.URL, bytes.NewBuffer(jsonData))
if err != nil {
err = fmt.Errorf("%w: %s", ErrSystem, err.Error())
err = errors.Join(ErrSystem, err)
if z.logger != nil {
z.logger.LogError(requestID, transactionID, proID, err, params)
}
@@ -126,7 +126,7 @@ func (z *ZhichaService) CallAPI(ctx context.Context, proID string, params map[st
// 发送请求
response, err := client.Do(req)
if err != nil {
err = fmt.Errorf("%w: %s", ErrSystem, err.Error())
err = errors.Join(ErrSystem, err)
if z.logger != nil {
z.logger.LogError(requestID, transactionID, proID, err, params)
}
@@ -137,7 +137,7 @@ func (z *ZhichaService) CallAPI(ctx context.Context, proID string, params map[st
// 读取响应
respBody, err := io.ReadAll(response.Body)
if err != nil {
err = fmt.Errorf("%w: %s", ErrSystem, err.Error())
err = errors.Join(ErrSystem, err)
if z.logger != nil {
z.logger.LogError(requestID, transactionID, proID, err, params)
}
@@ -152,7 +152,7 @@ func (z *ZhichaService) CallAPI(ctx context.Context, proID string, params map[st
// 检查HTTP状态码
if response.StatusCode != http.StatusOK {
err = fmt.Errorf("%w: HTTP状态码 %d", ErrDatasource, response.StatusCode)
err = errors.Join(ErrDatasource, fmt.Errorf("HTTP状态码 %d", response.StatusCode))
if z.logger != nil {
z.logger.LogError(requestID, transactionID, proID, err, params)
}
@@ -162,7 +162,7 @@ func (z *ZhichaService) CallAPI(ctx context.Context, proID string, params map[st
// 解析响应
var zhichaResp ZhichaResp
if err := json.Unmarshal(respBody, &zhichaResp); err != nil {
err = fmt.Errorf("%w: 响应解析失败: %s", ErrSystem, err.Error())
err = errors.Join(ErrSystem, fmt.Errorf("响应解析失败: %s", err.Error()))
if z.logger != nil {
z.logger.LogError(requestID, transactionID, proID, err, params)
}

View File

@@ -243,6 +243,51 @@ func (h *ApiHandler) DecryptParams(c *gin.Context) {
h.responseBuilder.Success(c, decryptedData, "解密成功")
}
// GetFormConfig 获取指定API的表单配置
// @Summary 获取表单配置
// @Description 获取指定API的表单配置用于前端动态生成表单
// @Tags API调试
// @Accept json
// @Produce json
// @Security Bearer
// @Param api_code path string true "API代码"
// @Success 200 {object} map[string]interface{} "获取成功"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 401 {object} map[string]interface{} "未授权"
// @Failure 404 {object} map[string]interface{} "API接口不存在"
// @Router /api/v1/form-config/{api_code} [get]
func (h *ApiHandler) GetFormConfig(c *gin.Context) {
userID := h.getCurrentUserID(c)
if userID == "" {
h.responseBuilder.Unauthorized(c, "用户未登录")
return
}
apiCode := c.Param("api_code")
if apiCode == "" {
h.responseBuilder.BadRequest(c, "API代码不能为空")
return
}
h.logger.Info("获取表单配置", zap.String("api_code", apiCode), zap.String("user_id", userID))
// 获取表单配置
config, err := h.appService.GetFormConfig(c.Request.Context(), apiCode)
if err != nil {
h.logger.Error("获取表单配置失败", zap.String("api_code", apiCode), zap.String("user_id", userID), zap.Error(err))
h.responseBuilder.BadRequest(c, "获取表单配置失败")
return
}
if config == nil {
h.responseBuilder.BadRequest(c, "API接口不存在")
return
}
h.logger.Info("获取表单配置成功", zap.String("api_code", apiCode), zap.String("user_id", userID), zap.Int("field_count", len(config.Fields)))
h.responseBuilder.Success(c, config, "获取表单配置成功")
}
// getCurrentUserID 获取当前用户ID
func (h *ApiHandler) getCurrentUserID(c *gin.Context) string {
if userID, exists := c.Get("user_id"); exists {

View File

@@ -10,10 +10,10 @@ import (
// ApiRoutes API路由注册器
type ApiRoutes struct {
apiHandler *handlers.ApiHandler
authMiddleware *middleware.JWTAuthMiddleware
apiHandler *handlers.ApiHandler
authMiddleware *middleware.JWTAuthMiddleware
domainAuthMiddleware *middleware.DomainAuthMiddleware
logger *zap.Logger
logger *zap.Logger
}
// NewApiRoutes 创建API路由注册器
@@ -24,10 +24,10 @@ func NewApiRoutes(
logger *zap.Logger,
) *ApiRoutes {
return &ApiRoutes{
apiHandler: apiHandler,
authMiddleware: authMiddleware,
apiHandler: apiHandler,
authMiddleware: authMiddleware,
domainAuthMiddleware: domainAuthMiddleware,
logger: logger,
logger: logger,
}
}
@@ -40,6 +40,9 @@ func (r *ApiRoutes) Register(router *sharedhttp.GinRouter) {
{
apiGroup.POST("/:api_name", r.domainAuthMiddleware.Handle(""), r.apiHandler.HandleApiCall)
// 表单配置接口(用于前端动态生成表单)
apiGroup.GET("/form-config/:api_code", r.authMiddleware.Handle(), r.apiHandler.GetFormConfig)
// 加密接口(用于前端调试)
apiGroup.POST("/encrypt", r.authMiddleware.Handle(), r.apiHandler.EncryptParams)

View File

@@ -88,6 +88,9 @@ westdex:
info: { max_size: 100, max_backups: 3, max_age: 28, compress: true }
error: { max_size: 200, max_backups: 10, max_age: 90, compress: true }
warn: { max_size: 100, max_backups: 3, max_age: 28, compress: true }
# 新增:请求和响应日志的独立配置
request_log_config: { max_size: 100, max_backups: 5, max_age: 30, compress: true }
response_log_config: { max_size: 100, max_backups: 5, max_age: 30, compress: true }
zhicha:
logging:
@@ -100,6 +103,9 @@ zhicha:
info: { max_size: 100, max_backups: 3, max_age: 28, compress: true }
error: { max_size: 200, max_backups: 10, max_age: 90, compress: true }
warn: { max_size: 100, max_backups: 3, max_age: 28, compress: true }
# 新增:请求和响应日志的独立配置
request_log_config: { max_size: 100, max_backups: 5, max_age: 30, compress: true }
response_log_config: { max_size: 100, max_backups: 5, max_age: 30, compress: true }
yushan:
logging:

View File

@@ -14,15 +14,21 @@ logs/
│ ├── westdex/ # westdex 服务日志
│ │ ├── westdex_info.log
│ │ ├── westdex_error.log
│ │ ── westdex_warn.log
│ │ ── westdex_warn.log
│ │ ├── westdex_request.log # 新增:请求日志文件
│ │ └── westdex_response.log # 新增:响应日志文件
│ ├── zhicha/ # zhicha 服务日志
│ │ ├── zhicha_info.log
│ │ ├── zhicha_error.log
│ │ ── zhicha_warn.log
│ │ ── zhicha_warn.log
│ │ ├── zhicha_request.log # 新增:请求日志文件
│ │ └── zhicha_response.log # 新增:响应日志文件
│ └── yushan/ # yushan 服务日志
│ ├── yushan_info.log
│ ├── yushan_error.log
── yushan_warn.log
── yushan_warn.log
│ ├── yushan_request.log # 新增:请求日志文件
│ └── yushan_response.log # 新增:响应日志文件
```
## 配置示例
@@ -59,6 +65,17 @@ westdex:
max_backups: 3
max_age: 28
compress: true
# 新增:请求和响应日志的独立配置
request_log_config:
max_size: 100
max_backups: 5
max_age: 30
compress: true
response_log_config:
max_size: 100
max_backups: 5
max_age: 30
compress: true
# zhicha 配置
zhicha:

View File

@@ -19,6 +19,9 @@ type ExternalServiceLoggingConfig struct {
UseDaily bool `yaml:"use_daily"`
EnableLevelSeparation bool `yaml:"enable_level_separation"`
LevelConfigs map[string]ExternalServiceLevelFileConfig `yaml:"level_configs"`
// 新增:请求和响应日志的独立配置
RequestLogConfig ExternalServiceLevelFileConfig `yaml:"request_log_config"`
ResponseLogConfig ExternalServiceLevelFileConfig `yaml:"response_log_config"`
}
// ExternalServiceLevelFileConfig 外部服务级别文件配置
@@ -34,6 +37,9 @@ type ExternalServiceLogger struct {
logger *zap.Logger
config ExternalServiceLoggingConfig
serviceName string
// 新增:用于区分请求和响应日志的字段
requestLogger *zap.Logger
responseLogger *zap.Logger
}
// NewExternalServiceLogger 创建外部服务日志器
@@ -64,6 +70,21 @@ func NewExternalServiceLogger(config ExternalServiceLoggingConfig) (*ExternalSer
return nil, fmt.Errorf("创建基础logger失败: %w", err)
}
// 创建请求和响应日志器
requestLogger, err := createRequestLogger(serviceLogDir, config)
if err != nil {
// 如果创建失败使用基础logger作为备选
requestLogger = baseLogger
fmt.Printf("创建请求日志器失败使用基础logger: %v\n", err)
}
responseLogger, err := createResponseLogger(serviceLogDir, config)
if err != nil {
// 如果创建失败使用基础logger作为备选
responseLogger = baseLogger
fmt.Printf("创建响应日志器失败使用基础logger: %v\n", err)
}
// 如果启用级别分离,创建文件输出
if config.EnableLevelSeparation {
core := createSeparatedCore(serviceLogDir, config)
@@ -72,9 +93,11 @@ func NewExternalServiceLogger(config ExternalServiceLoggingConfig) (*ExternalSer
// 创建日志器实例
logger := &ExternalServiceLogger{
logger: baseLogger,
config: config,
serviceName: config.ServiceName,
logger: baseLogger,
config: config,
serviceName: config.ServiceName,
requestLogger: requestLogger,
responseLogger: responseLogger,
}
// 如果启用按天分隔,启动定时清理任务
@@ -85,6 +108,72 @@ func NewExternalServiceLogger(config ExternalServiceLoggingConfig) (*ExternalSer
return logger, nil
}
// createRequestLogger 创建请求日志器
func createRequestLogger(logDir string, config ExternalServiceLoggingConfig) (*zap.Logger, error) {
// 创建编码器
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.TimeKey = "timestamp"
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
// 使用默认配置如果未指定
requestConfig := config.RequestLogConfig
if requestConfig.MaxSize == 0 {
requestConfig.MaxSize = 100
}
if requestConfig.MaxBackups == 0 {
requestConfig.MaxBackups = 5
}
if requestConfig.MaxAge == 0 {
requestConfig.MaxAge = 30
}
// 创建请求日志文件写入器
requestWriter := createFileWriter(logDir, "request", requestConfig, config.ServiceName, config.UseDaily)
// 创建请求日志核心
requestCore := zapcore.NewCore(
zapcore.NewJSONEncoder(encoderConfig),
zapcore.AddSync(requestWriter),
zapcore.InfoLevel,
)
return zap.New(requestCore), nil
}
// createResponseLogger 创建响应日志器
func createResponseLogger(logDir string, config ExternalServiceLoggingConfig) (*zap.Logger, error) {
// 创建编码器
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.TimeKey = "timestamp"
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
// 使用默认配置如果未指定
responseConfig := config.ResponseLogConfig
if responseConfig.MaxSize == 0 {
responseConfig.MaxSize = 100
}
if responseConfig.MaxBackups == 0 {
responseConfig.MaxBackups = 5
}
if responseConfig.MaxAge == 0 {
responseConfig.MaxAge = 30
}
// 创建响应日志文件写入器
responseWriter := createFileWriter(logDir, "response", responseConfig, config.ServiceName, config.UseDaily)
// 创建响应日志核心
responseCore := zapcore.NewCore(
zapcore.NewJSONEncoder(encoderConfig),
zapcore.AddSync(responseWriter),
zapcore.InfoLevel,
)
return zap.New(responseCore), nil
}
// createSeparatedCore 创建分离的日志核心
func createSeparatedCore(logDir string, config ExternalServiceLoggingConfig) zapcore.Core {
// 创建编码器
@@ -97,6 +186,10 @@ func createSeparatedCore(logDir string, config ExternalServiceLoggingConfig) zap
infoWriter := createFileWriter(logDir, "info", config.LevelConfigs["info"], config.ServiceName, config.UseDaily)
errorWriter := createFileWriter(logDir, "error", config.LevelConfigs["error"], config.ServiceName, config.UseDaily)
warnWriter := createFileWriter(logDir, "warn", config.LevelConfigs["warn"], config.ServiceName, config.UseDaily)
// 新增:请求和响应日志的独立文件输出
requestWriter := createFileWriter(logDir, "request", config.RequestLogConfig, config.ServiceName, config.UseDaily)
responseWriter := createFileWriter(logDir, "response", config.ResponseLogConfig, config.ServiceName, config.UseDaily)
// 修复:创建真正的级别分离核心
// 使用自定义的LevelEnabler来确保每个Core只处理特定级别的日志
@@ -118,8 +211,21 @@ func createSeparatedCore(logDir string, config ExternalServiceLoggingConfig) zap
&levelEnabler{minLevel: zapcore.WarnLevel, maxLevel: zapcore.WarnLevel}, // 只接受WARN级别
)
// 使用 zapcore.NewTee 合并核心,现在每个核心只会处理自己级别的日志
return zapcore.NewTee(infoCore, errorCore, warnCore)
// 新增:请求和响应日志核心
requestCore := zapcore.NewCore(
zapcore.NewJSONEncoder(encoderConfig),
zapcore.AddSync(requestWriter),
&requestResponseEnabler{logType: "request"}, // 只接受请求日志
)
responseCore := zapcore.NewCore(
zapcore.NewJSONEncoder(encoderConfig),
zapcore.AddSync(responseWriter),
&requestResponseEnabler{logType: "response"}, // 只接受响应日志
)
// 使用 zapcore.NewTee 合并核心,现在每个核心只会处理自己类型的日志
return zapcore.NewTee(infoCore, errorCore, warnCore, requestCore, responseCore)
}
// levelEnabler 自定义级别过滤器,确保只接受指定级别的日志
@@ -133,6 +239,17 @@ func (l *levelEnabler) Enabled(level zapcore.Level) bool {
return level >= l.minLevel && level <= l.maxLevel
}
// requestResponseEnabler 自定义日志类型过滤器,确保只接受特定类型的日志
type requestResponseEnabler struct {
logType string
}
// Enabled 实现 zapcore.LevelEnabler 接口
func (r *requestResponseEnabler) Enabled(level zapcore.Level) bool {
// 请求和响应日志通常是INFO级别
return level == zapcore.InfoLevel
}
// createFileWriter 创建文件写入器
func createFileWriter(logDir, level string, config ExternalServiceLevelFileConfig, serviceName string, useDaily bool) *lumberjack.Logger {
// 使用默认配置如果未指定
@@ -176,7 +293,7 @@ func createFileWriter(logDir, level string, config ExternalServiceLevelFileConfi
// LogRequest 记录请求日志
func (e *ExternalServiceLogger) LogRequest(requestID, transactionID, apiCode string, url interface{}, params interface{}) {
e.logger.Info(fmt.Sprintf("%s API请求", e.serviceName),
e.requestLogger.Info(fmt.Sprintf("%s API请求", e.serviceName),
zap.String("service", e.serviceName),
zap.String("request_id", requestID),
zap.String("transaction_id", transactionID),
@@ -189,7 +306,7 @@ func (e *ExternalServiceLogger) LogRequest(requestID, transactionID, apiCode str
// LogResponse 记录响应日志
func (e *ExternalServiceLogger) LogResponse(requestID, transactionID, apiCode string, statusCode int, response []byte, duration time.Duration) {
e.logger.Info(fmt.Sprintf("%s API响应", e.serviceName),
e.responseLogger.Info(fmt.Sprintf("%s API响应", e.serviceName),
zap.String("service", e.serviceName),
zap.String("request_id", requestID),
zap.String("transaction_id", transactionID),
@@ -203,7 +320,7 @@ func (e *ExternalServiceLogger) LogResponse(requestID, transactionID, apiCode st
// LogResponseWithID 记录包含响应ID的响应日志
func (e *ExternalServiceLogger) LogResponseWithID(requestID, transactionID, apiCode string, statusCode int, response []byte, duration time.Duration, responseID string) {
e.logger.Info(fmt.Sprintf("%s API响应", e.serviceName),
e.responseLogger.Info(fmt.Sprintf("%s API响应", e.serviceName),
zap.String("service", e.serviceName),
zap.String("request_id", requestID),
zap.String("transaction_id", transactionID),

View File

@@ -6,10 +6,9 @@
```
internal/shared/validator/
├── validator.go # HTTP请求验证器主逻辑
├── validator.go # 统一校验器主逻辑(包含所有功能)
├── custom_validators.go # 自定义验证器实现
├── translations.go # 中文翻译
├── business.go # 业务逻辑验证接口
└── README.md # 使用说明
```
@@ -22,9 +21,9 @@ internal/shared/validator/
- 统一的错误响应格式
### 2. 业务逻辑验证
- 独立的业务验证
- 可在任何地方调用的验证方法
- 独立的业务验证方法,可在任何地方调用
- 丰富的预定义验证规则
- 与标签验证使用相同的校验逻辑
### 3. 自定义验证规则
- 手机号验证 (`phone`)
@@ -106,35 +105,32 @@ type ProductCommand struct {
### 3. 业务逻辑验证
在Service中使用
在Service中使用统一的校验方法
```go
import "tyapi-server/internal/shared/validator"
type UserService struct {
businessValidator *validator.BusinessValidator
}
func NewUserService() *UserService {
return &UserService{
businessValidator: validator.NewBusinessValidator(),
}
// 不再需要单独的businessValidator
}
func (s *UserService) ValidateUserData(phone, password string) error {
// 验证手机号
if err := s.businessValidator.ValidatePhone(phone); err != nil {
// 直接使用包级别的校验方法
if err := validator.ValidatePhone(phone); err != nil {
return fmt.Errorf("手机号验证失败: %w", err)
}
// 验证密码强度
if err := s.businessValidator.ValidatePassword(password); err != nil {
if err := validator.ValidatePassword(password); err != nil {
return fmt.Errorf("密码验证失败: %w", err)
}
// 验证结构体
userData := UserData{Phone: phone, Password: password}
if err := s.businessValidator.ValidateStruct(userData); err != nil {
// 也可以使用结构体验证
userData := struct {
Phone string `validate:"phone"`
Password string `validate:"strong_password"`
}{Phone: phone, Password: password}
if err := validator.GetGlobalValidator().Struct(userData); err != nil {
return fmt.Errorf("用户数据验证失败: %w", err)
}
@@ -142,13 +138,12 @@ func (s *UserService) ValidateUserData(phone, password string) error {
}
func (s *UserService) ValidateEnterpriseInfo(code, idCard string) error {
// 验证统一社会信用代码
if err := s.businessValidator.ValidateSocialCreditCode(code); err != nil {
// 直接使用包级别的校验方法
if err := validator.ValidateSocialCreditCode(code); err != nil {
return err
}
// 验证身份证号
if err := s.businessValidator.ValidateIDCard(idCard); err != nil {
if err := validator.ValidateIDCard(idCard); err != nil {
return err
}
@@ -156,6 +151,27 @@ func (s *UserService) ValidateEnterpriseInfo(code, idCard string) error {
}
```
### 4. 处理器中的验证
在API处理器中可以直接使用结构体验证
```go
// 在 flxg5a3b_processor.go 中
func ProcessFLXG5A3BRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
var paramsDto dto.FLXG5A3BReq
if err := json.Unmarshal(params, &paramsDto); err != nil {
return nil, errors.Join(processors.ErrSystem, err)
}
// 使用统一的校验器验证
if err := deps.Validator.ValidateStruct(paramsDto); err != nil {
return nil, errors.Join(processors.ErrInvalidParam, err)
}
// ... 继续业务逻辑
}
```
## 🔧 可用的验证规则
### 标准验证规则
@@ -208,23 +224,33 @@ fx.Provide(
),
```
业务验证器可以在需要时创建:
```go
bv := validator.NewBusinessValidator()
```
## 📝 最佳实践
1. **DTO验证**: 在DTO中使用binding标签进行声明式验证
2. **业务验证**: 在业务逻辑中使用BusinessValidator进行程序化验证
3. **错误处理**: 验证错误会自动返回统一格式的HTTP响应
4. **性能**: 验证器实例可以复用,建议在依赖注入中管理
2. **业务验证**: 在业务逻辑中直接使用 `validator.ValidateXXX()` 方法
3. **统一性**: 所有校验都使用同一个校验器实例,确保规则一致
4. **错误处理**: 验证错误会自动返回统一格式的HTTP响应
## 🧪 测试示例
参考 `examples/validator_usage.go` 文件中的完整使用示例。
```go
// 测试自定义校验规则
func TestCustomValidators(t *testing.T) {
validator.InitGlobalValidator()
// 测试手机号验证
err := validator.ValidatePhone("13800138000")
if err != nil {
t.Errorf("有效手机号验证失败: %v", err)
}
err = validator.ValidatePhone("12345")
if err == nil {
t.Error("无效手机号应该验证失败")
}
}
```
---
这个验证器包提供了完整的验证解决方案既可以用于HTTP请求的自动验证也可以在业务逻辑中进行程序化验证确保数据的完整性和正确性。
这个验证器包现在提供了完整的统一解决方案既可以用于HTTP请求的自动验证也可以在业务逻辑中进行程序化验证确保数据的完整性和正确性。

View File

@@ -1,180 +0,0 @@
package validator
import (
"testing"
"time"
"github.com/go-playground/validator/v10"
)
func TestValidateAuthDate(t *testing.T) {
validate := validator.New()
validate.RegisterValidation("auth_date", validateAuthDate)
today := time.Now().Format("20060102")
yesterday := time.Now().AddDate(0, 0, -1).Format("20060102")
tomorrow := time.Now().AddDate(0, 0, 1).Format("20060102")
lastWeek := time.Now().AddDate(0, 0, -7).Format("20060102")
nextWeek := time.Now().AddDate(0, 0, 7).Format("20060102")
tests := []struct {
name string
authDate string
wantErr bool
}{
{
name: "今天到今天 - 有效",
authDate: today + "-" + today,
wantErr: false,
},
{
name: "昨天到今天 - 有效",
authDate: yesterday + "-" + today,
wantErr: false,
},
{
name: "今天到明天 - 有效",
authDate: today + "-" + tomorrow,
wantErr: false,
},
{
name: "上周到今天 - 有效",
authDate: lastWeek + "-" + today,
wantErr: false,
},
{
name: "今天到下周 - 有效",
authDate: today + "-" + nextWeek,
wantErr: false,
},
{
name: "昨天到明天 - 有效",
authDate: yesterday + "-" + tomorrow,
wantErr: false,
},
{
name: "明天到后天 - 无效(不包括今天)",
authDate: tomorrow + "-" + time.Now().AddDate(0, 0, 2).Format("20060102"),
wantErr: true,
},
{
name: "上周到昨天 - 无效(不包括今天)",
authDate: lastWeek + "-" + yesterday,
wantErr: true,
},
{
name: "格式错误 - 缺少连字符",
authDate: "2024010120240131",
wantErr: true,
},
{
name: "格式错误 - 多个连字符",
authDate: "20240101-20240131-20240201",
wantErr: true,
},
{
name: "格式错误 - 日期长度不对",
authDate: "202401-20240131",
wantErr: true,
},
{
name: "格式错误 - 非数字",
authDate: "20240101-2024013A",
wantErr: true,
},
{
name: "无效日期 - 2月30日",
authDate: "20240230-20240301",
wantErr: true,
},
{
name: "无效日期 - 13月",
authDate: "20241301-20241331",
wantErr: true,
},
{
name: "开始日期晚于结束日期",
authDate: "20240131-20240101",
wantErr: true,
},
{
name: "空字符串 - 由required处理",
authDate: "",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validate.Var(tt.authDate, "auth_date")
if (err != nil) != tt.wantErr {
t.Errorf("validateAuthDate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestParseYYYYMMDD(t *testing.T) {
tests := []struct {
name string
dateStr string
want time.Time
wantErr bool
}{
{
name: "有效日期",
dateStr: "20240101",
want: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
wantErr: false,
},
{
name: "闰年2月29日",
dateStr: "20240229",
want: time.Date(2024, 2, 29, 0, 0, 0, 0, time.UTC),
wantErr: false,
},
{
name: "非闰年2月29日",
dateStr: "20230229",
want: time.Time{},
wantErr: true,
},
{
name: "长度错误",
dateStr: "202401",
want: time.Time{},
wantErr: true,
},
{
name: "非数字",
dateStr: "2024010A",
want: time.Time{},
wantErr: true,
},
{
name: "无效月份",
dateStr: "20241301",
want: time.Time{},
wantErr: true,
},
{
name: "无效日期",
dateStr: "20240230",
want: time.Time{},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseYYYYMMDD(tt.dateStr)
if (err != nil) != tt.wantErr {
t.Errorf("parseYYYYMMDD() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && !got.Equal(tt.want) {
t.Errorf("parseYYYYMMDD() = %v, want %v", got, tt.want)
}
})
}
}

View File

@@ -1,108 +0,0 @@
package validator
import (
"testing"
"github.com/go-playground/validator/v10"
)
func TestValidateAuthorizationURL(t *testing.T) {
validate := validator.New()
RegisterCustomValidators(validate)
tests := []struct {
name string
url string
wantErr bool
}{
{
name: "有效的PDF URL",
url: "https://example.com/document.pdf",
wantErr: false,
},
{
name: "有效的JPG URL",
url: "https://example.com/image.jpg",
wantErr: false,
},
{
name: "有效的JPEG URL",
url: "https://example.com/image.jpeg",
wantErr: false,
},
{
name: "有效的PNG URL",
url: "https://example.com/image.png",
wantErr: false,
},
{
name: "有效的BMP URL",
url: "https://example.com/image.bmp",
wantErr: false,
},
{
name: "HTTP协议的PDF URL",
url: "http://example.com/document.pdf",
wantErr: false,
},
{
name: "带查询参数的PDF URL",
url: "https://example.com/document.pdf?version=1.0",
wantErr: false,
},
{
name: "带路径的PDF URL",
url: "https://example.com/files/documents/contract.pdf",
wantErr: false,
},
{
name: "无效的URL格式",
url: "not-a-url",
wantErr: true,
},
{
name: "不支持的文件类型",
url: "https://example.com/document.doc",
wantErr: true,
},
{
name: "不支持的文件类型2",
url: "https://example.com/document.txt",
wantErr: true,
},
{
name: "没有文件扩展名",
url: "https://example.com/document",
wantErr: true,
},
{
name: "FTP协议不支持",
url: "ftp://example.com/document.pdf",
wantErr: true,
},
{
name: "空字符串",
url: "",
wantErr: true,
},
{
name: "大写扩展名",
url: "https://example.com/document.PDF",
wantErr: false,
},
{
name: "混合大小写扩展名",
url: "https://example.com/document.JpG",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validate.Var(tt.url, "authorization_url")
if (err != nil) != tt.wantErr {
t.Errorf("validateAuthorizationURL() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}

View File

@@ -1,239 +0,0 @@
package validator
import (
"fmt"
"net/url"
"regexp"
"strings"
"github.com/go-playground/validator/v10"
)
// BusinessValidator 业务验证器
type BusinessValidator struct {
validator *validator.Validate
}
// NewBusinessValidator 创建业务验证器
func NewBusinessValidator() *BusinessValidator {
validate := validator.New()
RegisterCustomValidators(validate)
return &BusinessValidator{
validator: validate,
}
}
// ValidateStruct 验证结构体
func (bv *BusinessValidator) ValidateStruct(data interface{}) error {
return bv.validator.Struct(data)
}
// ValidateField 验证单个字段
func (bv *BusinessValidator) ValidateField(field interface{}, tag string) error {
return bv.validator.Var(field, tag)
}
// 以下是具体的业务验证方法,可以在业务逻辑中直接调用
// ValidatePhone 验证手机号
func (bv *BusinessValidator) ValidatePhone(phone string) error {
if phone == "" {
return fmt.Errorf("手机号不能为空")
}
matched, _ := regexp.MatchString(`^1[3-9]\d{9}$`, phone)
if !matched {
return fmt.Errorf("手机号格式不正确")
}
return nil
}
// ValidatePassword 验证密码强度
func (bv *BusinessValidator) ValidatePassword(password string) error {
if password == "" {
return fmt.Errorf("密码不能为空")
}
if len(password) < 8 {
return fmt.Errorf("密码长度不能少于8位")
}
hasUpper := regexp.MustCompile(`[A-Z]`).MatchString(password)
hasLower := regexp.MustCompile(`[a-z]`).MatchString(password)
hasDigit := regexp.MustCompile(`\d`).MatchString(password)
if !hasUpper {
return fmt.Errorf("密码必须包含大写字母")
}
if !hasLower {
return fmt.Errorf("密码必须包含小写字母")
}
if !hasDigit {
return fmt.Errorf("密码必须包含数字")
}
return nil
}
// ValidateUsername 验证用户名
func (bv *BusinessValidator) ValidateUsername(username string) error {
if username == "" {
return fmt.Errorf("用户名不能为空")
}
matched, _ := regexp.MatchString(`^[a-zA-Z][a-zA-Z0-9_]{2,19}$`, username)
if !matched {
return fmt.Errorf("用户名格式不正确只能包含字母、数字、下划线且必须以字母开头长度3-20位")
}
return nil
}
// ValidateSocialCreditCode 验证统一社会信用代码
func (bv *BusinessValidator) ValidateSocialCreditCode(code string) error {
if code == "" {
return fmt.Errorf("统一社会信用代码不能为空")
}
matched, _ := regexp.MatchString(`^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$`, code)
if !matched {
return fmt.Errorf("统一社会信用代码格式不正确必须是18位统一社会信用代码")
}
return nil
}
// ValidateIDCard 验证身份证号
func (bv *BusinessValidator) ValidateIDCard(idCard string) error {
if idCard == "" {
return fmt.Errorf("身份证号不能为空")
}
matched, _ := regexp.MatchString(`^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\dXx]$`, idCard)
if !matched {
return fmt.Errorf("身份证号格式不正确必须是18位身份证号")
}
return nil
}
// ValidateUUID 验证UUID
func (bv *BusinessValidator) ValidateUUID(uuid string) error {
if uuid == "" {
return fmt.Errorf("UUID不能为空")
}
matched, _ := regexp.MatchString(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`, uuid)
if !matched {
return fmt.Errorf("UUID格式不正确")
}
return nil
}
// ValidateURL 验证URL
func (bv *BusinessValidator) ValidateURL(urlStr string) error {
if urlStr == "" {
return fmt.Errorf("URL不能为空")
}
_, err := url.ParseRequestURI(urlStr)
if err != nil {
return fmt.Errorf("URL格式不正确: %v", err)
}
return nil
}
// ValidateProductCode 验证产品代码
func (bv *BusinessValidator) ValidateProductCode(code string) error {
if code == "" {
return fmt.Errorf("产品代码不能为空")
}
matched, _ := regexp.MatchString(`^[a-zA-Z0-9_\-\(\)]{3,50}$`, code)
if !matched {
return fmt.Errorf("产品代码格式不正确只能包含字母、数字、下划线、连字符、中英文括号长度3-50位")
}
return nil
}
// ValidateEmail 验证邮箱
func (bv *BusinessValidator) ValidateEmail(email string) error {
if email == "" {
return fmt.Errorf("邮箱不能为空")
}
matched, _ := regexp.MatchString(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`, email)
if !matched {
return fmt.Errorf("邮箱格式不正确")
}
return nil
}
// ValidateSortOrder 验证排序方向
func (bv *BusinessValidator) ValidateSortOrder(sortOrder string) error {
if sortOrder == "" {
return nil // 允许为空
}
if sortOrder != "asc" && sortOrder != "desc" {
return fmt.Errorf("排序方向必须是 asc 或 desc")
}
return nil
}
// ValidatePrice 验证价格
func (bv *BusinessValidator) ValidatePrice(price float64) error {
if price < 0 {
return fmt.Errorf("价格不能为负数")
}
return nil
}
// ValidateStringLength 验证字符串长度
func (bv *BusinessValidator) ValidateStringLength(str string, fieldName string, min, max int) error {
length := len(strings.TrimSpace(str))
if min > 0 && length < min {
return fmt.Errorf("%s长度不能少于%d位", fieldName, min)
}
if max > 0 && length > max {
return fmt.Errorf("%s长度不能超过%d位", fieldName, max)
}
return nil
}
// ValidateRequired 验证必填字段
func (bv *BusinessValidator) ValidateRequired(value interface{}, fieldName string) error {
if value == nil {
return fmt.Errorf("%s不能为空", fieldName)
}
switch v := value.(type) {
case string:
if strings.TrimSpace(v) == "" {
return fmt.Errorf("%s不能为空", fieldName)
}
case *string:
if v == nil || strings.TrimSpace(*v) == "" {
return fmt.Errorf("%s不能为空", fieldName)
}
}
return nil
}
// ValidateRange 验证数值范围
func (bv *BusinessValidator) ValidateRange(value float64, fieldName string, min, max float64) error {
if value < min {
return fmt.Errorf("%s不能小于%v", fieldName, min)
}
if value > max {
return fmt.Errorf("%s不能大于%v", fieldName, max)
}
return nil
}
// ValidateSliceNotEmpty 验证切片不为空
func (bv *BusinessValidator) ValidateSliceNotEmpty(slice interface{}, fieldName string) error {
if slice == nil {
return fmt.Errorf("%s不能为空", fieldName)
}
switch v := slice.(type) {
case []string:
if len(v) == 0 {
return fmt.Errorf("%s不能为空", fieldName)
}
case []int:
if len(v) == 0 {
return fmt.Errorf("%s不能为空", fieldName)
}
}
return nil
}

View File

@@ -488,3 +488,234 @@ func validateReturnURL(fl validator.FieldLevel) bool {
return true
}
// ================ 统一的业务校验方法 ================
// ValidatePhone 验证手机号
func ValidatePhone(phone string) error {
if phone == "" {
return fmt.Errorf("手机号不能为空")
}
matched, _ := regexp.MatchString(`^1[3-9]\d{9}$`, phone)
if !matched {
return fmt.Errorf("手机号格式不正确")
}
return nil
}
// ValidatePassword 验证密码强度
func ValidatePassword(password string) error {
if password == "" {
return fmt.Errorf("密码不能为空")
}
if len(password) < 8 {
return fmt.Errorf("密码长度不能少于8位")
}
hasUpper := regexp.MustCompile(`[A-Z]`).MatchString(password)
hasLower := regexp.MustCompile(`[a-z]`).MatchString(password)
hasDigit := regexp.MustCompile(`\d`).MatchString(password)
if !hasUpper {
return fmt.Errorf("密码必须包含大写字母")
}
if !hasLower {
return fmt.Errorf("密码必须包含小写字母")
}
if !hasDigit {
return fmt.Errorf("密码必须包含数字")
}
return nil
}
// ValidateUsername 验证用户名
func ValidateUsername(username string) error {
if username == "" {
return fmt.Errorf("用户名不能为空")
}
matched, _ := regexp.MatchString(`^[a-zA-Z][a-zA-Z0-9_]{2,19}$`, username)
if !matched {
return fmt.Errorf("用户名格式不正确只能包含字母、数字、下划线且必须以字母开头长度3-20位")
}
return nil
}
// ValidateSocialCreditCode 验证统一社会信用代码
func ValidateSocialCreditCode(code string) error {
if code == "" {
return fmt.Errorf("统一社会信用代码不能为空")
}
matched, _ := regexp.MatchString(`^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$`, code)
if !matched {
return fmt.Errorf("统一社会信用代码格式不正确必须是18位统一社会信用代码")
}
return nil
}
// ValidateIDCard 验证身份证号
func ValidateIDCard(idCard string) error {
if idCard == "" {
return fmt.Errorf("身份证号不能为空")
}
matched, _ := regexp.MatchString(`^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\dXx]$`, idCard)
if !matched {
return fmt.Errorf("身份证号格式不正确必须是18位身份证号")
}
return nil
}
// ValidateUUID 验证UUID
func ValidateUUID(uuid string) error {
if uuid == "" {
return fmt.Errorf("UUID不能为空")
}
matched, _ := regexp.MatchString(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`, uuid)
if !matched {
return fmt.Errorf("UUID格式不正确")
}
return nil
}
// ValidateURL 验证URL
func ValidateURL(urlStr string) error {
if urlStr == "" {
return fmt.Errorf("URL不能为空")
}
_, err := url.ParseRequestURI(urlStr)
if err != nil {
return fmt.Errorf("URL格式不正确: %v", err)
}
return nil
}
// ValidateProductCode 验证产品代码
func ValidateProductCode(code string) error {
if code == "" {
return fmt.Errorf("产品代码不能为空")
}
matched, _ := regexp.MatchString(`^[a-zA-Z0-9_\-\(\)]{3,50}$`, code)
if !matched {
return fmt.Errorf("产品代码格式不正确只能包含字母、数字、下划线、连字符、中英文括号长度3-50位")
}
return nil
}
// ValidateEmail 验证邮箱
func ValidateEmail(email string) error {
if email == "" {
return fmt.Errorf("邮箱不能为空")
}
matched, _ := regexp.MatchString(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`, email)
if !matched {
return fmt.Errorf("邮箱格式不正确")
}
return nil
}
// ValidateSortOrder 验证排序方向
func ValidateSortOrder(sortOrder string) error {
if sortOrder == "" {
return nil // 允许为空
}
if sortOrder != "asc" && sortOrder != "desc" {
return fmt.Errorf("排序方向必须是 asc 或 desc")
}
return nil
}
// ValidatePrice 验证价格
func ValidatePrice(price float64) error {
if price < 0 {
return fmt.Errorf("价格不能为负数")
}
return nil
}
// ValidateStringLength 验证字符串长度
func ValidateStringLength(str string, fieldName string, min, max int) error {
length := len(strings.TrimSpace(str))
if min > 0 && length < min {
return fmt.Errorf("%s长度不能少于%d位", fieldName, min)
}
if max > 0 && length > max {
return fmt.Errorf("%s长度不能超过%d位", fieldName, max)
}
return nil
}
// ValidateRequired 验证必填字段
func ValidateRequired(value interface{}, fieldName string) error {
if value == nil {
return fmt.Errorf("%s不能为空", fieldName)
}
switch v := value.(type) {
case string:
if strings.TrimSpace(v) == "" {
return fmt.Errorf("%s不能为空", fieldName)
}
case *string:
if v == nil || strings.TrimSpace(*v) == "" {
return fmt.Errorf("%s不能为空", fieldName)
}
}
return nil
}
// ValidateRange 验证数值范围
func ValidateRange(value float64, fieldName string, min, max float64) error {
if value < min {
return fmt.Errorf("%s不能小于%v", fieldName, min)
}
if value > max {
return fmt.Errorf("%s不能大于%v", fieldName, max)
}
return nil
}
// ValidateSliceNotEmpty 验证切片不为空
func ValidateSliceNotEmpty(slice interface{}, fieldName string) error {
if slice == nil {
return fmt.Errorf("%s不能为空", fieldName)
}
switch v := slice.(type) {
case []string:
if len(v) == 0 {
return fmt.Errorf("%s不能为空", fieldName)
}
case []int:
if len(v) == 0 {
return fmt.Errorf("%s不能为空", fieldName)
}
}
return nil
}
// ================ 便捷的校验器创建函数 ================
// NewBusinessValidator 创建业务验证器(保持向后兼容)
func NewBusinessValidator() *BusinessValidator {
// 确保全局校验器已初始化
InitGlobalValidator()
return &BusinessValidator{
validator: GetGlobalValidator(), // 使用全局校验器
}
}
// BusinessValidator 业务验证器(保持向后兼容)
type BusinessValidator struct {
validator *validator.Validate
}
// ValidateStruct 验证结构体
func (bv *BusinessValidator) ValidateStruct(data interface{}) error {
return bv.validator.Struct(data)
}
// ValidateField 验证单个字段
func (bv *BusinessValidator) ValidateField(field interface{}, tag string) error {
return bv.validator.Var(field, tag)
}

View File

@@ -3,6 +3,7 @@ package validator
import (
"fmt"
"strings"
"sync"
"tyapi-server/internal/shared/interfaces"
@@ -14,6 +15,58 @@ import (
zh_translations "github.com/go-playground/validator/v10/translations/zh"
)
// 全局变量声明
var (
globalValidator *validator.Validate
globalTranslator ut.Translator
once sync.Once
)
// InitGlobalValidator 初始化全局校验器(线程安全)
func InitGlobalValidator() {
once.Do(func() {
// 1. 创建新的校验器实例
globalValidator = validator.New()
// 2. 创建中文翻译器
zhLocale := zh.New()
uni := ut.New(zhLocale, zhLocale)
globalTranslator, _ = uni.GetTranslator("zh")
// 3. 注册官方中文翻译
zh_translations.RegisterDefaultTranslations(globalValidator, globalTranslator)
// 4. 注册自定义校验规则
RegisterCustomValidators(globalValidator)
// 5. 注册自定义中文翻译
RegisterCustomTranslations(globalValidator, globalTranslator)
// 6. 设置到Gin全局校验器确保Gin使用我们的校验器
if binding.Validator.Engine() != nil {
// 如果Gin已经初始化则替换其校验器
ginValidator := binding.Validator.Engine().(*validator.Validate)
*ginValidator = *globalValidator
}
})
}
// GetGlobalValidator 获取全局校验器实例
func GetGlobalValidator() *validator.Validate {
if globalValidator == nil {
InitGlobalValidator()
}
return globalValidator
}
// GetGlobalTranslator 获取全局翻译器实例
func GetGlobalTranslator() ut.Translator {
if globalTranslator == nil {
InitGlobalValidator()
}
return globalTranslator
}
// RequestValidator HTTP请求验证器
type RequestValidator struct {
response interfaces.ResponseBuilder
@@ -23,29 +76,13 @@ type RequestValidator struct {
// NewRequestValidator 创建HTTP请求验证器
func NewRequestValidator(response interfaces.ResponseBuilder) interfaces.RequestValidator {
// 创建中文locale
zhLocale := zh.New()
uni := ut.New(zhLocale, zhLocale)
// 获取中文翻译器
trans, _ := uni.GetTranslator("zh")
// 获取gin默认的validator实例
ginValidator := binding.Validator.Engine().(*validator.Validate)
// 注册官方中文翻译
zh_translations.RegisterDefaultTranslations(ginValidator, trans)
// 注册自定义验证器到gin的全局validator
RegisterCustomValidators(ginValidator)
// 注册自定义翻译
RegisterCustomTranslations(ginValidator, trans)
// 确保全局校验器已初始化
InitGlobalValidator()
return &RequestValidator{
response: response,
translator: trans,
validator: ginValidator,
translator: globalTranslator, // 使用全局翻译器
validator: globalValidator, // 使用全局校验器
}
}